Java流的两个列表之间的compare属性相等,并返回true或false

需要:
class Pair {
    String key;
    String value;
}
List<Pair> list1 = Stream.of(
        new Pair("key1", "value1"),
        new Pair("key2", "value2")
    )
    .collect(Collections.toList());

List<Pair> list2 = Stream.of(
        new Pair("key1", "value2"),
        new Pair("key2", "value3")
    )
    .collect(Collections.toList());

我想对中的值进行一些更改list2,然后将其与进行比较list1

我想检查list2中与list1相比,列表中所有项目的属性键是否都没有更改。list2中只能更改value属性。

并且list2中的项目数与list1相同。list1.size()= list2.size()

我正在尝试编写一个返回布尔值的流,但是在某个地方我一定弄错了

list1.stream()
    .allMatch(pair2->  list2.stream()
        .anyMatch(pair->pair.getKey().equals(pair2.getKey())));
    // Need to add list size() comparison too

更新:我设法编写了一个这样的流,junit测试似乎可以正常工作,尽管它不比较与ernest_k答案相同索引的项目。

   list1.stream()
        .allMatch(pair -> list2.stream()
            .anyMatch(pair2-> pair.getKey().equals(pair2.getKey()) ) && list1.size()== list2.size()
            ));

ernest_k:

您可以使用:

boolean result = list1.size() == list2.size() && 
        IntStream.range(0, list1.size())
            .allMatch(i -> list1.get(i).getKey().equals(list2.get(i).getKey()));

由于您必须逐个元素比较lists元素,因此不能使用嵌套流(如您的示例中那样),只能简单地进行笛卡尔联接,如果每个list1元素具有相同键的任何 list2元素,则返回true (而您希望该比较具有索引意识)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章