美文网首页
java8 操作

java8 操作

作者: Cool尘 | 来源:发表于2020-08-19 22:25 被阅读0次

public class Main {

public static void main(String[] args) {

    List<Apple> appleList = initAppleInfo();

    // 1. 分组
    Map<Integer, List<Apple>> groupList = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
    System.out.println(groupList);
    System.out.println("============================================");

    // 2. List 转Map
    Map<Integer, Apple> mapList = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a, (k1, k2) -> k1));
    System.out.println(mapList);
    System.out.println("============================================");

    // 3. 过滤Filter
    List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());
    System.out.println(filterList);
    System.out.println("============================================");

    // 4. 求和
    BigDecimal reduce = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
    System.out.println(reduce);
    System.out.println("============================================");

    // 5. 查找流中最大最小值
    Optional<Apple> maxResult = appleList.stream().max(Comparator.comparing(Apple::getMoney));
    //Optional<Apple> maxResult = appleList.stream().collect(Collectors.maxBy(Comparator.comparing(Apple::getMoney)));
    //Optional<Apple> minResult = appleList.stream().collect(Collectors.minBy(Comparator.comparing(Apple::getMoney)));
    Optional<Apple> minResult = appleList.stream().min(Comparator.comparing(Apple::getMoney));
    maxResult.ifPresent(System.out::println);
    minResult.ifPresent(System.out::println);
    System.out.println("============================================");

    // 6. 去重
    ArrayList<Apple> distinctList = appleList.stream().collect(Collectors.collectingAndThen(
            Collectors.toCollection(() -> new TreeSet<>(Comparator.comparingLong(Apple::getId))), ArrayList::new
    ));
    distinctList.forEach(System.out::println);
    System.out.println("============================================");


}


public static List<Apple> initAppleInfo() {
    // 存放apple对象集合
    List<Apple> appleList = new ArrayList<>();
    Apple apple1 = new Apple(1, "苹果1", new BigDecimal("3.25"), 10);
    Apple apple12 = new Apple(1, "苹果2", new BigDecimal("1.35"), 20);
    Apple apple2 = new Apple(2, "香蕉", new BigDecimal("2.89"), 30);
    Apple apple3 = new Apple(3, "荔枝", new BigDecimal("9.99"), 40);
    appleList.add(apple1);
    appleList.add(apple12);
    appleList.add(apple2);
    appleList.add(apple3);
    return appleList;
}

}

相关文章

网友评论

      本文标题:java8 操作

      本文链接:https://www.haomeiwen.com/subject/iscjjktx.html