JAVA笔记-java8常用操作
一、数组转List
List<Integer> intList= Arrays.stream(new int[] { 1, 2, 3}).boxed().collect(Collectors.toList());
List<Long> longList= Arrays.stream(new long[] { 1, 2, 3 }).boxed().collect(Collectors.toList());
List<Double> doubleList= Arrays.stream(new double[] {1,2,3}).boxed().collect(Collectors.toList());
String[] arrays = {"a", "b", "c"};
List<String> stringList= Stream.of(arrays).collect(Collectors.toList());
short[]、byte[]、char[]在1.8中目前不支持
老方式:List<String> strList = Arrays.asList(arrays);
List<String> newStrList= new ArrayList<>(arrays.length);Collections.addAll(newStrList, arrays);
二、List转数组
Long[] longArray = longList.stream().toArray(Long[]::new);
三、List<对象>转Map
Map<String, Object> map=list.stream().collect(Collectors.toMap(Object::getId, item -> item));
Map<String, String> map=list.stream().collect(Collectors.toMap(Object::getId, Object::getId));
四、去重
List<String> list = new ArrayList<String>();list.stream().distinct().collect(Collectors.toList())
五、两个List<Integer>比较值是否相等
List<Integer> list1 = List.of(1, 2, 3); List<Integer> list1 = List.of(3, 2, 1);
list1.equals(list2); // 有顺序 list1.stream().sorted().collect(Collectors.toList()).equals(list1.stream().sorted().collect(Collectors.toList())); // 无顺序
六、枚举查找
Arrays.stream(values()).filter(item -> item.name().equals(value)).findFirst().orElse(null);
七、查找
List.of(1, 2, 3).stream().filter(c -> c == 1).findFirst().orElse(null);
八、分组
Map<Integer, List<Object>> listMap = objList.stream().collect(Collectors.groupingBy(Object::getId));
Map<Integer, List<String>> listMap = objList.stream().collect(Collectors.groupingBy(Object::getId,Collectors.mapping(Object::getName,Collectors.toList())));
九、求和
// 对象属性求和:
List<Object> list = new ArrayList<>();
BigDecimal total = list.stream().map(Object::getXx).reduce(BigDecimal.ZERO, (b1, b2) -> b1.add(ObjectUtil.isNull(b2) ? BigDecimal.ZERO : b2));
total.setScale(0, RoundingMode.DOWN); // 保留整数
十、排序
// 默认
list.stream().sorted(Comparator.comparing(Dto::getXx)).collect(Collectors.toList());
// 倒序
list.stream().sorted(Comparator.comparing(Dto::getXx).reversed()).collect(Collectors.toList());
// null处理
list.stream().sorted(Comparator.comparing(Dto::getXx, Comparator.nullsFirst(Date::compareTo))).collect(Collectors.toList());
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)