常用方法集锦(自用)

java8 map根据key排序和根据value排序

1、根据key排序

Map<String,String> result = new HashMap<>();
 
Map<String,String> map = new HashMap<>();
 
map.entrySet().stream()
    .sorted(Map.Entry.comparingByKey())
        .forEachOrdered(x->result.put(x.getKey(),x.getValue()));

2、根据value排序

Map<String, Integer> valueResult = new HashMap<>();
Map<String, Integer> map = new HashMap<>();
map.entrySet().stream()
    .sorted(Map.Entry
        .comparingByValue())
        .forEachOrdered(b->valueResult.put(b.getKey(), b.getValue()));

3, 根据value排序(倒序)-----工具类

 // Map的value值降序排序
    public static <K, V extends Comparable<? super V>> Map<K, V> sortDescend(Map<K, V> map) {
        List<Map.Entry<K, V>> list = new ArrayList<>(map.entrySet());
        Collections.sort(list, (o1, o2) -> {
            int compare = (o1.getValue()).compareTo(o2.getValue());
            return -compare;
        });

        Map<K, V> returnMap = new LinkedHashMap<K, V>();
        for (Map.Entry<K, V> entry : list) {
            returnMap.put(entry.getKey(), entry.getValue());
        }
        return returnMap;
    }

list排序

1,正序

List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge))
                .collect(Collectors.toList());

2 , 倒序

List<User> newList = list.stream().sorted(Comparator.comparing(User::getAge).reversed())
                .collect(Collectors.toList());
// 按成绩升序
List<Student> students3 = students.stream().sorted(Comparator.comparing(Student::getScore))
        .collect(Collectors.toList());
System.out.println("按成绩升序");
students3.forEach(System.out::println);
// 按成绩降序
List<Student> students4 =
        students.stream().sorted(Comparator.comparing(Student::getScore).reversed())
                .collect(Collectors.toList());
System.out.println("按成绩降序");
students4.forEach(System.out::println);
// 按成绩升序,再按年龄升序
List<Student> students5 = students.stream()
        .sorted(Comparator.comparing(Student::getScore).thenComparing(Student::getAge))
        .collect(Collectors.toList());
System.out.println("按成绩升序,再按年龄升序");
students5.forEach(System.out::println);
// 按成绩升序,再按年龄降序
List<Student> students6 = students.stream().sorted((s1, s2) -> {
    if (s1.getScore() != s2.getScore()) {
        return (int) (s1.getScore() - s2.getScore());
    } else {
        return (s2.getAge() - s1.getAge());
    }
}).collect(Collectors.toList());
System.out.println("按成绩升序,再按年龄降序");
students6.forEach(System.out::println);

3 分组

Map<String, List<UserQuestion>> groupBy = userQuestions.stream()
                .collect(Collectors.groupingBy(UserQuestion::getUserClass));
// 按条件学生成绩是否大于等于60,划分为2个组
Map<Boolean, List<Student>> studentScorePart = students.stream()
        .collect(Collectors.partitioningBy(student -> student.getScore() >= 60));
// 按性别分组
Map<String, List<Student>> studentSexMap =
        students.stream().collect(Collectors.groupingBy(Student::getSex));
// 按年龄分组
Map<Integer, List<Student>> studentAgeMap =
        students.stream().collect(Collectors.groupingBy(Student::getAge));
// 先按性别分组,再按年龄分组
Map<String, Map<Integer, List<Student>>> collect = students.stream().collect(
        Collectors.groupingBy(Student::getSex, Collectors.groupingBy(Student::getAge)));
System.out.println("按条件学生成绩是否大于等于60,划分为2个组:");
studentScorePart.forEach((aBoolean, students7) -> {
    System.out.println("成绩大于等于60?:" + aBoolean);
    students7.forEach(System.out::println);
});
System.out.println("按性别分组:");
studentSexMap.forEach((sex, students7) -> {
    System.out.println("性别?:" + sex);
    students7.forEach(System.out::println);
});
System.out.println("按年龄分组:");
studentAgeMap.forEach((age, students7) -> {
    System.out.println("年龄:" + age);
    students7.forEach(System.out::println);
});
System.out.println("先按性别分组,再按年龄分组:");
collect.forEach((sex, integerListMap) -> {
    System.out.println("性别:" + sex);
    integerListMap.forEach((age, students7) -> {
        System.out.println("年龄:" + age);
        students7.forEach(System.out::println);
    });
});

4 反射,获得对象中每个属性的值

 public static Object bigDecimalToZero(Object obj){
        if (obj != null){
            Class<?> clazz = obj.getClass();
            //获取所有该对象的属性值
            Field[] fields = clazz.getDeclaredFields();
            //遍历属性值,取得所有属性为null的值的
            for (Field field : fields) {
                //可访问私有变量
                field.setAccessible(true);
                //获取属性类型
                String type = field.getGenericType().toString();
                //如果type是类类型,则前面包含“class”,后面跟类名
                if("class java.math.BigDecimal".equals(type)){
                    String methodName = field.getName().replaceFirst(field.getName().substring(0, 1), field.getName().substring(0, 1).toUpperCase());
                    try {
                        Method methodGet = clazz.getMethod("get" + methodName);
                        //调用getter方法获取属性值
                        if(methodGet.invoke(obj)==null){
                                field.set(obj,new BigDecimal(0));
                        }

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return obj;
    }

**

多字段排序

**

  teamList = teamList.stream().sorted((a, b) -> {
                    Integer aIsWhole = a.getIsWhole();
                    Integer bIsWhole = b.getIsWhole();
                    int compareTo = aIsWhole.compareTo(bIsWhole);
                    if (compareTo != 0) {
                        return compareTo;
                    }
                    Date aTeamEndDate = a.getEndDate();
                    Date bTeamEndDate = b.getEndDate();
                    int compareTo1 = aTeamEndDate.compareTo(bTeamEndDate);
                    return compareTo1;
                }).collect(Collectors.toList());

list<对象>转list

public static <T extends SysAuth> List<Map<String,Object>> EntityConvertMap(List<SysAuth> list){
        List<Map<String,Object>> l = new LinkedList<>();
        try {
            for(SysAuth t : list){
                Map<String,Object> map = new HashMap<>();
                Method[] methods = t.getClass().getMethods();
                for (Method method : methods) {
                    if (method.getName().startsWith("get")) {
                        String name = method.getName().substring(3);
                        name = name.substring(0, 1).toLowerCase() + name.substring(1);
                        Object value = method.invoke(t);
                        map.put(name,value);
                    }
                }
                l.add(map);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return l;
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值