JAVA笔记-java8常用操作
一、数组转ListListInteger intList Arrays.stream(new int[] { 1, 2, 3}).boxed().collect(Collectors.toList());ListLong longList Arrays.stream(new long[] { 1, 2, 3 }).boxed().collect(Collectors.toList());ListDouble doubleList Arrays.stream(new double[] {1,2,3}).boxed().collect(Collectors.toList());String[] arrays {a, b, c};ListString stringList Stream.of(arrays).collect(Collectors.toList());short[]、byte[]、char[]在1.8中目前不支持老方式ListString strList Arrays.asList(arrays);ListString newStrList new ArrayList(arrays.length);Collections.addAll(newStrList, arrays);二、List转数组Long[] longArray longList.stream().toArray(Long[]::new);三、List对象转MapMapString, Object maplist.stream().collect(Collectors.toMap(Object::getId, item - item));MapString, String maplist.stream().collect(Collectors.toMap(Object::getId, Object::getId));如果Key是元素本身可以使用 x-x或者直接使用Function.identity()表示不做任何转换四、去重ListString list new ArrayListString();list.stream().distinct().collect(Collectors.toList())五、两个ListInteger比较值是否相等ListInteger list1 List.of(1, 2, 3); ListInteger 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);八、分组MapInteger, ListObject listMap objList.stream().collect(Collectors.groupingBy(Object::getId));MapInteger, ListString listMap objList.stream().collect(Collectors.groupingBy(Object::getId,Collectors.mapping(Object::getName,Collectors.toList())));九、求和// 对象属性求和 ListObject 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());