gpt4 book ai didi

java - 使用流检测实体的多个属性的重复项

转载 作者:行者123 更新时间:2023-12-01 12:47:48 24 4
gpt4 key购买 nike

我想通过其内部的多个属性来检测任何重复的对象,例如:

class Person{
String name,
Integer age,
String address

//constructors
//getters setters
}

现在,在以上 3 个参数中,我想使用 2 个参数来检查重复项,它们是 {name 和 age}我尝试使用流来实现这一点,但似乎应该有更简单的使用流的方法。

当前方法:

List<Person> personList = new ArrayList<>();
personList.add(new Person("name1", 10, "address1"));
personList.add(new Person("name2", 20, "address1"));
personList.add(new Person("name1", 10, "address2"));
personList.add(new Person("name3", 10, "address2"));

// Want to detect name1 and age 10 as a duplicate entry

Map<String, Map<Integer, List<Person>> nameAgePersonListMap = personList.stream()
.collect(Collectors.groupingBy(i -> i.getName(), Collectors.groupingBy(i -> i.getAge())));
// and later checking each element for size() > 1

在这个用例中是否有更有效的方法来确定重复项?

最佳答案

如果在分组和识别重复项之后键不是很重要,您可以执行与以下相同的操作:

Map<List<?>, List<Person>> nameAgePersonListMap = personList.stream()
.collect(Collectors.groupingBy(i -> Arrays.asList(i.getName(), i.getAge())));

我说“很多”,因为您仍然可以访问 key,只是必须将特定属性强制转换到它的类型中才能检索它,因为entry -> (String)entry.getKey().get(0) 将返回分组中使用的名称。

在执行类似的操作时特别有用

personList.stream()
.collect(Collectors.groupingBy(i -> Arrays.asList(i.getName(), i.getAge())))
.entrySet().stream()
.filter(entry -> entry.getValue().size() > 1)
.map(Map.Entry::getValue)
...

关于java - 使用流检测实体的多个属性的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62679493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com