关于复杂的过滤器java流

时间:2018-02-07 21:46:50

标签: java filter java-8 java-stream

我有关于过滤器的问题,我写了两个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());

但这是我的问题我想要一个人员名单,例如这个人住在一条街道上,包含&#34; ol&#34;而且我不知道如何用java流写这个,过去我在sql中使用了内连接,但是现在用Java流我怎么能做这个请求??? 谢谢你的帮助

1 个答案:

答案 0 :(得分:4)

你可以试试这个:

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());