使用filter()取出所需数据

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

使用filter()取出所需数据

笨蛋的生活   2022-06-03 我要评论

使用filter()取出自己所需数据

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");
        }
   }
}

结果

java8 filter使用心得

如果A集合元素数量10个,filter满足条件为5个,没有赋值新集合,那么A还是原来的10个,如果赋值给B集合,B集合为5个;

如果A集合10个,filter满足条件为5个,赋值给B集合,遍历B集合,对这5个元素进行了修改,那么A集合中的5个元素也会同时修改。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们