1. 程式人生 > >java8實現各種List操作

java8實現各種List操作

spa 實現 max groupby 處理 present 最小 erl IV

利用java8新特性,可以用簡潔高效的代碼來實現一些數據處理。
定義1個Apple對象:

public class Apple {
    private Integer id;
    private String name;
    private BigDecimal money;
    private Integer num;
    public Apple(Integer id, String name, BigDecimal money, Integer num) {
        this.id = id;
        this.name = name;
        this
.money = money; this.num = num; } }

添加一些測試數據:


Apple apple1 =  new Apple(1,"蘋果1",new BigDecimal("3.25"),10);
Apple apple2 = new Apple(1,"蘋果2",new BigDecimal("1.35"),20);
Apple apple3 =  new Apple(2,"香蕉",new BigDecimal("2.89"),30);
Apple apple4 =  new Apple(3,"荔枝",new BigDecimal("9.99"),40);

List<Apple> appleList = Lists.newArrayList
(apple1, apple2, apple3, apple4);

1、分組
List裏面的對象元素,以某個屬性來分組,例如,以id分組,將id相同的放在一起:

//List 以ID分組 Map<Integer,List<Apple>>
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));

2、List轉Map
id為key,apple對象為value,可以這麽做:

/**
 * List -> Map
* 需要註意的是: * toMap 如果集合對象有重復的key,會報錯Duplicate key .... * apple1,apple12的id都為1。 * 可以用 (k1,k2)->k1 來設置,如果有重復的key,則保留key1,舍棄key2 */ Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));

3、過濾Filter
從集合中過濾出來符合條件的元素:

//過濾出符合條件的數據
List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("香蕉")).collect(Collectors.toList());

4.求和
將集合中的數據按照某個屬性求和:

//計算 總金額
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);

5.查找流中最大 最小值
Collectors.maxBy 和 Collectors.minBy 來計算流中的最大或最小值。

Optional<Dish> maxDish = Dish.menu.stream().
      collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories)));
maxDish.ifPresent(System.out::println);

Optional<Dish> minDish = Dish.menu.stream().
      collect(Collectors.minBy(Comparator.comparing(Dish::getCalories)));
minDish.ifPresent(System.out::println);

6.去重

// 根據id去重  
     List<Person> unique = appleList.stream().collect(  
                collectingAndThen(toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new)  
        );  

參考:https://blog.csdn.net/lu930124/article/details/77595585

java8實現各種List操作