gpt4 book ai didi

java - 关于复杂的过滤java流

转载 作者:行者123 更新时间:2023-11-30 06:45:37 25 4
gpt4 key购买 nike

我有一个关于filter的问题,我写了两个POJO:

@Getter
@Setter
@AllArgsConstructor
@ToString
class Person {
private int id;
private String firstName;
private List<Address> address;
}

@Getter
@Setter
@AllArgsConstructor
@ToString
class Address {
private int id;
private String street;
private String city;
}

我写了两个合集:

   Address address1 = new Address(1, "Main street", "London");
Address address2 = new Address(2, "Hollywood Boolevard", "Los Angeles");
Address address3=new Address(3,"Rue de la paix","Paris");

List<Person> personList = Arrays.asList(
new Person(1, "Tom", Arrays.asList(address1)),
new Person(2, "Fred", Arrays.asList(address2)),
new Person(3,"Beth",Arrays.asList(address1,address2)),
new Person(4,"Marc",Arrays.asList(address1,address3))
);

如果我想要所有地址的列表,使用

非常简单
 List<Address> addressList=personList.stream().map(Person::getAddress)
.flatMap(List::stream).collect(Collectors.toList());

但这是我的问题我想要一个人的列表,这个人居住在一条包含“ol”的街道上,我不知道如何用 java 流写这个,过去我在 sql 中使用 inner join但现在有了 Java 流,我该如何执行此请求???感谢您的帮助

最佳答案

你可以试试这个:

personList.stream()
// filter people who has an adress that contains "ol"
// you could also create a method on Person that check if has this address to make it more readable
.filter(p -> p.getAddress()
.stream()
.anyMatch(a -> a.getStreet().contains("ol")))
.collect(Collectors.toList());

更新:Person 上的方法示例:

class Person {
// ...
public boolean livesInStreet(String street) {
return this.address.stream().anyMatch(a -> a.getStreet().contains(street));
}
}

使用新方法:

personList.stream()
.filter(p -> p.livesInStreet("ol"))
.collect(Collectors.toList());

关于java - 关于复杂的过滤java流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48673794/

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