使用Stream对List<Map>排序

1、添加测试数据

    public static void main(String[] args) {
        List list = new ArrayList<>();
        Map map = new HashMap<>();
        Person p = new Person("玛卡巴卡","s5",7);
        map.put("name",p.name);
        map.put("no",p.no);
        map.put("age",p.age);
        list.add(map);
        map = new HashMap<>();
        p = new Person("唔西迪西","s7",8);
        map.put("name",p.name);
        map.put("no",p.no);
        map.put("age",p.age);
        list.add(map);
        map = new HashMap<>();
        p = new Person("叮叮车","s1",4);
        map.put("name",p.name);
        map.put("no",p.no);
        map.put("age",p.age);
        list.add(map);
        list.forEach(System.out::println);

    }

    static class Person{
        String name;
        String no;
        Integer age;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getNo() {
            return no;
        }

        public void setNo(String no) {
            this.no = no;
        }

        public Integer getAge() {
            return age;
        }

        public void setAge(Integer age) {
            this.age = age;
        }

        public Person(String name, String no, Integer age) {
            this.name = name;
            this.no = no;
            this.age = age;
        }

        @Override
        public String toString() {
            return "person{" +
                    "name='" + name + '\'' +
                    ", no='" + no + '\'' +
                    ", age=" + age +
                    '}';
        }
    }

输出如下 

使用Stream对List<Map>排序_第1张图片

1.1 按照no排序

        System.out.println("排序前");
        list.forEach(System.out::println);

        System.out.println("排序后1");
        List no = list.stream().sorted(comparing(l ->     l.get("no").toString())).collect(Collectors.toList());
        no.forEach(System.out::println);

        System.out.println("排序后2");
        List no1 = list.stream().sorted((map1, map2) -> {
            String time1 = map1.get("no").toString();
            String  time2 = map2.get("no").toString();
            return time1.compareTo(time2);
        }).collect(Collectors.toList());
        no1.forEach(System.out::println);

        System.out.println("排序后3");
        List no2 = list.stream().sorted((map1, map2) -> {
            int time1 = Integer.parseInt(map1.get("no").toString().replace("s",""));
            int  time2 = Integer.parseInt(map2.get("no").toString().replace("s",""));
            return time1 - time2;
        }).collect(Collectors.toList());
        no2.forEach(System.out::println);

 输出

使用Stream对List<Map>排序_第2张图片

使用(map1,map2)时,注意顺序就好

 

 

你可能感兴趣的:(list,数学建模,java)