list<map>类型根据某字段排序

        转换lamd表达式后: o1,o2代表第一个和第二个集合元素 然后获取对应的需要比较的数值,这里是用了long类型
Collections.sort(records, (o1, o2) -> {
    Long batchCode1 = (Long) o1.get("BATCH_CODE");//batchCode1是从你list里面拿出来的一个批次编号
    Long batchCode2 = (Long) o2.get("BATCH_CODE");//name1是从你list里面拿出来的第二个批次编号
    return batchCode1.compareTo(batchCode2);
});

                如果list集合中指定了map的参数类型:List>,建议如下写:

Collections.sort(list, new Comparator>() {
            public int compare(Map o1, Map o2) {
                //  o1,o2是list中的Map,可以在其内取得值,按其排序,此例为升序,s1和s2是排序字段值  
                Integer s1 = (Integer) o1.get("sequence");
                Integer s2 = (Integer) o2.get("sequence");
                return batchCode1.compareTo(batchCode2);
                }});

                如果不进行对应的map类型指定的话,可能会报异常: 

list根据多字段排序

排序: reversed()倒序,升序可去掉

List list=new ArrayList();
        User user1=new User(2021,new BigDecimal("201"),"jack");
        User user2=new User(2021,new BigDecimal("456"),"sun");
        User user3=new User(2020,new BigDecimal("1980"),"liwe");
        User user4=new User(2020,new BigDecimal("23"),"like");
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);
        System.out.println(list);
        list= (List) list.stream().sorted(Comparator.comparing(User::getYears).reversed().thenComparing(            User::getMoney,Comparator.reverseOrder())).collect(Collectors.toList());
 System.out.println(list);

手动去重

1.list对象去重

Person p1 = new Person(1l, "jack");
Person p2 = new Person(3l, "jack chou");
Person p3 = new Person(2l, "tom");
Person p4 = new Person(4l, "hanson");
Person p5 = new Person(5l, "胶布虫");

List persons = Arrays.asList(p1, p2, p3, p4, p5, p5, p1, p2, p2);

List personList = new ArrayList<>();
// 去重
persons.stream().forEach(
    p -> {
        if (!personList.contains(p)) {
            personList.add(p);
        }
    }
);
System.out.println(personList);

2.list属性去重

List list=new ArrayList<>();
        MongoUser mongoUser=new MongoUser();
        mongoUser.setId("1");
        mongoUser.setName("zhangsan");
        mongoUser.setMobile("111111");

        MongoUser mongoUser1=new MongoUser();
        mongoUser1.setId("2");
        mongoUser1.setName("zhangsan");
        mongoUser1.setMobile("222");
        list.add(mongoUser);
        list.add(mongoUser1);

        List unique = list.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<>(comparing(MongoUser::getName))), ArrayList::new)
        );
        System.out.println(unique);

你可能感兴趣的:(list,java,后端)