Java8Stream自定义复杂排序

@Test
    public void  testSet(){
        List<Map<String,Object>> list=new ArrayList<Map<String, Object>>();
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("name","name1");
        map.put("age",12);
        list.add(map);

        Map<String,Object> map2=new HashMap<String, Object>();
        map2.put("name","name2");
        map2.put("age",13);
        list.add(map2);

        System.out.println("排序前:"+list.toString());
        list=list.stream()
                //第一个排序条件
                //假设自定义对象为Obj,则可直接写为Obj::getName
                .sorted(Comparator.comparing(Application::getName)
                        //第二个排序条件(可一直延伸)
                        .thenComparing(Application::getAge).reversed()).collect(Collectors.toList());
        System.out.println("排序后:"+list.toString());
    }

    private static String getName(Map<String,Object> map){
        return (String) map.get("name");
    }

    private static int getAge(Map<String,Object> map){
        return (int) map.get("age");
    }

发表评论

电子邮件地址不会被公开。 必填项已用*标注