【发布时间】:2021-09-05 09:12:56
【问题描述】:
我有一个复杂的obj 对象,其中包含一个CountryUnit 对象,该对象包含countries 的集合。
countries 具有以下 countryValue 值:
countries == {
Country1 (countryValue == "A")
Country2 (countryValue == "B")
}
在这种情况下,我需要进行转换,以便结果集 countries 包含 countryValue 的值,这些值将替换为从 allowedCountryList 中随机选择的值。例如:
countries == {
Country1 (countryValue == "N")
Country2 (countryValue == "S")
}
然后我需要返回 obj 对象,并带有 countryValue 的新值。最简单的方法是什么?我有一段代码,但它不能正常工作。
SomeObject obj; // complex object that contains multiple levels, obj contains CountryUnit object
public class CountryUnit {
private Set<Country> countries = new HashSet<>();
// getters, setters
}
public class Country {
private String countryValue;
// getters, setters
}
我的代码:
List<String> CountryChecker = Arrays.asList("A", "B", "C");
List<String> allowedCountryList = Arrays.asList("L", "M", "N", "O", "P", "R", "S");
obj.getSomeSet().stream()
.map(CountryUnit::getCountries)
.flatMap(Set::stream)
.filter((x) -> CountryChecker.contains(x.getCountryValue()))
.map(y -> {
Random r = new Random();
int rCountry = r.nextInt(allowedCountryList.size());
y.setCountryValue(allowedCountryList.get(rCountry));
return y;
});
【问题讨论】:
标签: java collections stream