gpt4 book ai didi

java - 使用java流按相同类型的2个键分组

转载 作者:搜寻专家 更新时间:2023-11-01 01:12:03 24 4
gpt4 key购买 nike

使用 java 流,如何从一个列表创建一个映射以通过同一类上的 2 个键进行索引?

我在这里给出一个代码示例,我希望 map “personByName”通过名字或姓氏获取所有人,所以我想获取 3 个“steves”:当它是他们的名字或姓氏时。我不知道如何混合使用 2 个 Collectors.groupingBy。

public static class Person {
final String firstName;
final String lastName;

protected Person(String firstName, String lastName) {
super();
this.firstName = firstName;
this.lastName = lastName;
}

public String getFirstName() {
return firstName;
}

public String getLastName() {
return lastName;
}

}

@Test
public void testStream() {
List<Person> persons = Arrays.asList(
new Person("Bill", "Gates"),
new Person("Bill", "Steve"),
new Person("Steve", "Jobs"),
new Person("Steve", "Wozniac"));

Map<String, Set<Person>> personByFirstName = persons.stream().collect(Collectors.groupingBy(Person::getFirstName, Collectors.toSet()));
Map<String, Set<Person>> personByLastName = persons.stream().collect(Collectors.groupingBy(Person::getLastName, Collectors.toSet()));

Map<String, Set<Person>> personByName = persons.stream().collect(Collectors.groupingBy(Person::getLastName, Collectors.toSet()));// This is wrong, I want bot first and last name

Assert.assertEquals("we should search by firstName AND lastName", 3, personByName.get("Steve").size()); // This fails

}

我通过在 2 个 map 上循环找到了解决方法,但它不是面向流的。

最佳答案

你可以这样做:

Map<String, Set<Person>> personByName = persons.stream()
.flatMap(p -> Stream.of(new SimpleEntry<>(p.getFirstName(), p),
new SimpleEntry<>(p.getLastName(), p)))
.collect(Collectors.groupingBy(SimpleEntry::getKey,
Collectors.mapping(SimpleEntry::getValue, Collectors.toSet())));

假设您将 toString() 方法添加到 Person 类,然后您可以使用以下方法查看结果:

List<Person> persons = Arrays.asList(
new Person("Bill", "Gates"),
new Person("Bill", "Steve"),
new Person("Steve", "Jobs"),
new Person("Steve", "Wozniac"));

// code above here

personByName.entrySet().forEach(System.out::println);

输出

Steve=[Steve Wozniac, Bill Steve, Steve Jobs]
Jobs=[Steve Jobs]
Bill=[Bill Steve, Bill Gates]
Wozniac=[Steve Wozniac]
Gates=[Bill Gates]

关于java - 使用java流按相同类型的2个键分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55361841/

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