我有以下两个课程:
class Man {
private int id;
private String firstName;
private String lastName;
private int age;
private int countOfChildren;
private Address address;
}
class Address {
private Country country;
private City city;
private String street;
private long quantityOfPeople;
}
我不知道如何分组List< Man>由Address类的街道和城市字段.我该怎么做?@H_403_11@
最佳答案@H_403_11@
Collectors类提供了
Collectors.groupingBy(keyProvider,downstream)
,您可以使用它来按一对值进行分组.要配对两个值,您可以使用AbstractMap.SimpleEntry
,也可以实现自己的Pair< T,K>表示一对两个值的类(值得一提的是,如果要将其用作哈希映射中的键,则必须在Pair类中实现hashCode()和equals(object)方法).你想在一个键中配对的两个值必须实现hashCode()和equals(object)方法 – 在这种情况下值得使用不可变类.
整个分组部分可以通过以下方式完成:
final Map
在这个例子中,我使用AbstractMap.SimpleEntry来表示一对Country和street.它创建了一个映射,其中每个键都根据国家和街道对Man对象列表进行分组.您可以在下面找到完整的示例:
import java.util.AbstractMap;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
public class GroupByTest {
public static void main(String[] args) {
final List
当您运行此示例时,您将在控制台中执行以下操作:
People associated with Rome,Pepperoni 31:
Man{id=5,firstName='Arnold',lastName='Smoke',age=72,countOfChildren=3,address=Address{country=Country{name='Italy'},city=City{name='Rome'},street='Pepperoni 31',quantityOfPeople=10000}}
People associated with London,Test Street 3:
Man{id=6,firstName='Katy',lastName='Puppet',age=33,address=Address{country=Country{name='England'},city=City{name='London'},street='Test Street 3',quantityOfPeople=10000}}
People associated with Berlin,Volkswagen Platz 31:
Man{id=4,firstName='Vincent',lastName='Dog',age=43,countOfChildren=2,address=Address{country=Country{name='Germany'},city=City{name='Berlin'},street='Volkswagen Platz 31',Maine Strasse 32:
Man{id=2,firstName='Mary',lastName='Smith',age=54,countOfChildren=4,street='Maine Strasse 32',Test Street 2:
Man{id=1,firstName='John',lastName='Doe',age=20,countOfChildren=0,street='Test Street 2',quantityOfPeople=10000}}
Man{id=3,firstName='James',lastName='Rose',age=13,quantityOfPeople=10000}}
希望能帮助到你.@H_403_11@ 原文链接:https://www.f2er.com/java/437478.html