跳至主要內容

java

日常积累模板代码java约 368 字大约 1 分钟

lambda

// list 取出对应元素转为list
List<String> strList = demoList.stream().map(Demo::getStr)
.collect(Collectors.toList());

// list 根据某个字段去重
List<Demo> distinctList = demoList.stream()
.collect(Collectors.collectingAndThen(Collectors.toCollection(() 
-> new TreeSet<>(Comparator.comparing(Demo::getId))), ArrayList::new));

// list 转为map
// 优先取先出现key
Map<String, Demo> k1Map = demoList.stream().filter(Objects::nonNull)
.collect(Collectors.toMap(Demo::getStr, Function.identity(), 
(key1, key2) -> key1));

// 优先取后出现key
Map<String, Demo> k2Map = demoList.stream().filter(Objects::nonNull)
.collect(Collectors.toMap(Demo::getStr, Function.identity(), 
(key1, key2) -> key2));

// list 分组为 map
Map<Long, List<Demo>> demoHashMap = demoList.stream().filter(Objects::nonNull)
.collect(Collectors.groupingBy(Demo::getId));

// 将list 排序,并按照排序后的结果进行有序分组
LinkedHashMap<String, List<Demo>> demoLinkedMap = demoList.stream()
.sorted(Comparator.comparingLong(Demo::getId))
.collect(Collectors.groupingBy(Demo::getStr, LinkedHashMap::new, 
Collectors.toList()));

// 字符转为list
String ids = "1,2,3";

List<Long> idList = Arrays.stream(ids.split(","))
.map(s -> Long.parseLong(s.trim()))
.collect(Collectors.toList());

List<String> idStrList = Arrays.stream(ids.split(","))
.collect(Collectors.toList());

// 数组转list
String[] idArray = new String[]{"1", "2", "3"};

List<Long> idArrayList = Arrays.stream(idArray)
.map(s -> Long.parseLong(s.trim()))
.collect(Collectors.toList());

// 排序
List<Demo> ascList = demoList.stream()
.sorted(Comparator.comparing(Demo::getPrice))
.collect(Collectors.toList());

List<Demo> descList = demoList.stream()
.sorted(Comparator.comparing(Demo::getPrice).reversed())
.collect(Collectors.toList());

// 是否包含
boolean bool = demoList.stream()
.anyMatch(a -> "a".equals(a.getStr()));

// 获取最大值
Optional<Demo> maxDish = demoList.stream()
.max(Comparator.comparing(Demo::getPrice));

Optional<Demo> minDish = demoList.stream()
.min(Comparator.comparing(Demo::getPrice));

// 分组统计
Map<String, LongSummaryStatistics> longStatisticsMap = demoList.stream()
.collect(Collectors.groupingBy(Demo::getStr, 
Collectors.summarizingLong(Demo::getId)));

Map<String, Long> longSumMap = demoList.stream()
.collect(Collectors.groupingBy(Demo::getStr, 
Collectors.summingLong(Demo::getId)));

// 累加
BigDecimal sum = demoList.stream().map(Demo::getPrice)
.reduce(BigDecimal::add).orElse(BigDecimal.ZERO);

分批处理list

List<List<Demo>> partitions = ListUtils
.partition(records, 100);

partitions.forEach(item -> {});

遍历枚举

public static DemoEnum fromValue(Integer value) {
    if (value == null) {
      return null;
    }
    for (DemoEnum demo : DemoEnum.values()) {
        if (demo.getValue().equals(value)) {
            return demo;
        }
    }
    return null;
}