我想从特定键的属性创建值集合。方法以这种方式工作:
Collection<String> getValueOfKey(final Collection<Localization> input, final String key) {
return input.stream().map(l -> {
return l.getProperties();
}).map(p -> {
return p.getProperty(key, "");
}).collect(Collectors.toList());
}
首先,我想使用Collectors.toSet()
代替Collectors.toList()
,但后来我得到了错误的结果(它只是给了我en
的价值)。有人知道为什么我不能使用.toSet()
吗?
这是我的TestCode:
public class RowCreatorTest {
private final Properties fixturePropertieDe = new Properties();
private final Properties fixturePropertieEn = new Properties();
private final Localization de = new Localization(Languages.GERMAN, fixturePropertieDe);
private final Localization en = new Localization(Languages.ENGLISH, fixturePropertieEn);
private final RowCreator sut = new RowCreator();
@Before
public void prepareFixtures() {
fixturePropertieDe.put("key1", "foo1");
fixturePropertieDe.put("key3", "foo3");
fixturePropertieEn.put("key1", "bar1");
fixturePropertieEn.put("key2", "bar2");
}
@Test
public void getValueOfKey() {
assertThat(sut.getValueOfKey(Arrays.asList(de, en), "key1"), contains("foo1", "bar1"));
assertThat(sut.getValueOfKey(Arrays.asList(de, en), "key2"), contains("", "bar2"));
assertThat(sut.getValueOfKey(Arrays.asList(de, en), "key3"), contains("foo3", ""));
}
以下是测试内容的截图:test screenshot
答案 0 :(得分:4)
根据您发布的错误的链接(expected iterable containing ["foo1","bar1"] but item 0 was "bar1"
),断言期望两个值以指定的顺序出现(首先是“foo1”,然后是“bar1”),但是Set
s不维护顺序,并且在迭代Set
时首先出现“bar1”,因此断言失败。
因此问题在于断言,而不是toSet()
的使用。
例如,如果您使用Set
(将LinkedHashSet
替换为toSet()
),则可以根据广告订单强制toCollection(LinkedHashSet::new)
进行迭代。这将确保断言不会失败。