时间:2023-02-20 09:45:36 | 栏目:JAVA代码 | 点击:次
java8的filter()方法是取出自己所需的数据,返回满足条件里的数据
person.java
package com.it.pojo; import java.util.Comparator; import java.util.Objects; @Data @NoArgsConstructor @ToString public class Person { private String name; private Integer age; }
test.java
package com.it.test; import java.util.ArrayList; import java.util.List; import com.it.pojo.Person; import java.util.Comparator; import java.util.stream.Collectors; public class StreamTest { public static void main(String[] args) { Person person1 = new Person(); person1.setAge(21); person1.setName("21"); Person person2 = new Person(); person2.setAge(19); person2.setName("19"); Person person3 = new Person(); person3.setAge(19); person3.setName("20"); Person person4 = new Person(); person4.setAge(20); person4.setName("20"); Person person5 = new Person(); person5.setAge(19); person5.setName("18"); List<Person> people = new ArrayList<>(); people.add(person1); people.add(person2); people.add(person3); people.add(person4); people.add(person5); List<Person> collect1 = people.stream().filter((person) -> { return person.getName().equals("18"); //取姓名是18的Person数据 }).collect(Collectors.toList()); System.out.println(collect1); List<Person> collect2 = people.stream().filter((person) -> { return person.getAge().intValue()==19 && person.getName().equals("19"); }).collect(Collectors.toList()); System.out.println(collect2); List<Person> collect = people.stream().filter(person -> person.getName().equals("181") //测试不满足条件的list集合会是什么样的 ).collect(Collectors.toList()); System.out.println(collect); //集合size==0 if(collect.size()==0){ System.out.println("nihao"); } } }
结果
如果A集合元素数量10个,filter满足条件为5个,没有赋值新集合,那么A还是原来的10个,如果赋值给B集合,B集合为5个;
如果A集合10个,filter满足条件为5个,赋值给B集合,遍历B集合,对这5个元素进行了修改,那么A集合中的5个元素也会同时修改。