根据某个字段筛选list数据

//测试类

package test;

import java.util.ArrayList;
import java.util.List;

import org.junit.jupiter.api.Test;

public class TestLambda {
	
	@Test
	public void test() {
		List<Person>list=new ArrayList<Person>();
		list.add(new Person("张三",20,500));
		list.add(new Person("李四",40,600));
		list.add(new Person("赵四",35,500));
		list.add(new Person("王五",36,500));
		list.add(new Person("王七",30,600));
		list.add(new Person("旺旺",31,700));
		list.add(new Person("倪萍",35,500));
		List<Person>personList=getPersonList(list,new GetInfoByAge());
		System.out.println(list.toString());
		System.out.println("personList=========="+personList);
		personList.forEach(person->System.out.println("结果==="+person));
		
	}
	
	/**
	 * 匿名内部类实现
	 */
	@Test
	public void test2() {
		List<Person>list=new ArrayList<Person>();
		list.add(new Person("张三",20,500));
		list.add(new Person("李四",40,600));
		list.add(new Person("赵四",35,500));
		list.add(new Person("王五",36,500));
		list.add(new Person("王七",30,600));
		list.add(new Person("旺旺",31,700));
		list.add(new Person("倪萍",35,500));
		
		
		List<Person>list2=getPersonList(list,new MyPrivate<Person>() {
			@Override
			public boolean getInfo(Person t) {
				// TODO Auto-generated method stub
				return t.getAge()<=32;
			}
			
		});
		System.out.println("list2===="+list2);
		
	}
	/**
	 * lambda表达式实现
	 */
	@Test
	public void Test3() {
		List<Person>list=new ArrayList<Person>();
		list.add(new Person("张三",20,500));
		list.add(new Person("李四",40,600));
		list.add(new Person("赵四",35,500));
		list.add(new Person("王五",36,500));
		list.add(new Person("王七",30,600));
		list.add(new Person("旺旺",31,700));
		list.add(new Person("倪萍",35,500));
		
		List<Person>list3=getPersonList(list,(e)->e.getAge()>=40);
		System.out.println("list3======"+list3);
		
	}
	
	/**
	 * 判断方法
	 * @param list
	 * @param myPrivate
	 * @return
	 */
	public List<Person>getPersonList(List<Person>list,MyPrivate<Person> myPrivate){
		List<Person>personList=new ArrayList<Person>();
		for(Person person:list) {
			if(myPrivate.getInfo(person)){
				personList.add(person);
			}
		}
		return personList;
	}

}

  

  

  接口

package test;

public interface MyPrivate<T> {
	public boolean getInfo(T t);

}

  实现类

package test;

public class GetInfoByAge implements MyPrivate<Person>{

	@Override
	public boolean getInfo(Person p) {
		
		return p.getAge()>=35;
	}

}

  

根据某个字段筛选list数据

上一篇:Array类


下一篇:Vue 路由 04