java stream 2个list中某个字段比较
时间: 2024-05-03 15:22:45 浏览: 15
可以使用Java 8中的Stream API来比较两个List中某个字段的值。
假设有两个List,每个List中都包含一个Person对象,Person对象有一个名字属性。我们可以使用Stream API将两个List中的Person对象按名字进行比较。
代码示例:
```
List<Person> list1 = new ArrayList<>();
list1.add(new Person("Alice"));
list1.add(new Person("Bob"));
list1.add(new Person("Charlie"));
List<Person> list2 = new ArrayList<>();
list2.add(new Person("Bob"));
list2.add(new Person("Charlie"));
list2.add(new Person("David"));
List<String> names1 = list1.stream().map(Person::getName).collect(Collectors.toList());
List<String> names2 = list2.stream().map(Person::getName).collect(Collectors.toList());
names1.retainAll(names2);
System.out.println("共同的名字:" + names1);
```
在上面的代码中,我们首先使用Stream API将每个List中的Person对象的名字提取出来,然后使用retainAll()方法比较两个List中的名字是否相同,最后输出共同的名字。
输出结果:
```
共同的名字:[Bob, Charlie]
```
注意,这里我们只比较了名字是否相同,如果需要比较其他属性,可以在map()方法中指定相应的属性。