【java】使用lambda和函数接口Comparator

public class Demo {

    /*
     * 实现分组
     */
    @Test
    public void testWhat() {
     //注:Employee的属性有:{id,name,age,salary,deptId} List
<Employee> list = Arrays.asList( new Employee(0, "赵", 35, 5555,1), new Employee(1, "钱", 44, 5555,5), new Employee(2, "孙", 22, 5555,2), new Employee(3, "李", 26, 5555,1), new Employee(4, "周", 15, 5555,5), new Employee(5, "吴", 45, 5555,5) ); //需求1:按年龄排序 Collections.sort(list,(emp1,emp2)->emp1.getAge()>emp2.getAge()?1:-1); //升序 Collections.sort(list,(emp1,emp2)->emp1.getAge()>emp2.getAge()?-1:1); //降序 list.forEach(System.out::println); //需求2按部门分组 new What<Employee>().grouping(list,(e1,e2)->e1.getDepId()==e2.getDepId()?1:-1); } public class What<T>{ public void grouping(List<T>list,Comparator<T> comp) { List<List<T>> groups = new ArrayList<List<T>>(); for(T t:list) { boolean isGroupExists=false; for(List<T> group:groups) { if(comp.compare(t,group.get(0))>=0) { group.add(t); isGroupExists=true; break; } } if(!isGroupExists) { List<T> group=new ArrayList<T>(); group.add(t); groups.add(group); } } } } }

  注:Employee的属性有:{id,name,age,salary,deptId}

List<Employee> list = Arrays.asList(
    new Employee(0, "赵", 55, 5555,1),
    new Employee(0, "钱", 55, 5555,5),
    new Employee(0, "孙", 55, 5555,2),
    new Employee(0, "李", 55, 5555,1),
    new Employee(0, "周", 55, 5555,5),
    new Employee(0, "吴", 55, 5555,5)
    );

//需求1实现排序

 

 

原文地址:https://www.cnblogs.com/LightChan/p/8320356.html