通过两个属性查找重复对象

kko*_*kot 4 java java-8

考虑到我有一个像这样的 Person 对象列表:

Class Person {
  String fullName;
  String occupation;
  String hobby;
  int salary;
}
Run Code Online (Sandbox Code Playgroud)

使用java8流,如何仅通过fullName和occupation属性获取重复对象列表?

Dea*_*ool 7

通过使用 java-8Stream()Collectors.groupingBy()名字和职业

List<Person> duplicates = list.stream()
    .collect(Collectors.groupingBy(p -> p.getFullName() + "-" + p.getOccupation(), Collectors.toList()))
    .values()
    .stream()
    .filter(i -> i.size() > 1)
    .flatMap(j -> j.stream())
    .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)


Jor*_*nee 5

我需要在 fullName -occupation pair 中找出它们是否有任何重复,这必须是唯一的

基于此评论,您似乎并不真正关心哪些Person对象被复制,只是有任何对象。

在这种情况下,您可以使用有状态的anyMatch

Collection<Person> input = new ArrayList<>();

Set<List<String>> seen = new HashSet<>();
boolean hasDupes = input.stream()
                        .anyMatch(p -> !seen.add(List.of(p.fullName, p.occupation)));
Run Code Online (Sandbox Code Playgroud)

您可以将 aList用作包含您已经看到的fullName+occupation组合的集合的“键” 。如果再次看到此组合,您将立即返回true,否则您完成对元素的迭代并返回false