Java8--Lambada表達式對List的操作


 實體類:

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;
    }

    public Integer getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public BigDecimal getMoney() {
        return money;
    }

    public Integer getNum() {
        return num;
    }

    @Override
    public String toString() {
        return "Apple{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                ", num=" + num +
                '}';
    }
}
public class User {
    private String name;
    //age
    private int age;
    //分數
    private double fraction;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public double getFraction() {
        return fraction;
    }

    public User(String name, int age, double fraction) {
        this.name = name;
        this.age = age;
        this.fraction = fraction;
    }
}

填充List:

     List<Apple> appleList = new ArrayList<>();//存放apple對象集合

        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);

    
     List<User> userList = new ArrayList<>();
     userList.add(new User("a1", 22, 2.2));
     userList.add(new User("a2", 22, 2.5));
     userList.add(new User("a3", 40, 2.7));
     userList.add(new User("a4", 45, 2.8));

     List<String> list1 = new ArrayList<>();
     list1.add("111");
     list1.add("222");
     list1.add("333");

     List<String> list2 = new ArrayList<>();
     list2.add("111");
     list2.add("333");
     list2.add("444");

List -> Map:

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

        /**
         * List -> Map
         * 需要注意的是:
         * toMap 如果集合對象有重復的key,會報錯Duplicate key ....
         *  apple1,apple12的id都為1。
         *  可以用 (k1,k2)->k1 來設置,如果有重復的key,則保留key1,舍棄key2
         */
        Map<Integer, Apple> map = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a, (k1, k2) -> k1));
        for (Map.Entry<Integer, Apple> entry : map.entrySet()) {
            System.out.println("key:" + entry.getKey() + "\nvalue:" + entry.getValue());
        }

過濾、去重、計算、定位取、取某個元素重新組成List:

    //計算 總金額
        BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
        System.out.println("totalMoney:" + totalMoney);  //totalMoney:17.48

        //去重
        List<Apple> appleDistinctList = appleList.stream()
                .collect(Collectors.collectingAndThen
                        (Collectors.toCollection(() ->
                                        new TreeSet<>(Comparator.comparing(t -> t.getId()))),
                                ArrayList::new
                        )
                );
        System.out.println("appleDistinctList:" + appleDistinctList);

        //取出屬性中的某個值 重新組成list
        List<String> appleNameList = appleList.stream()
                .map(Apple::getName).collect(Collectors.toList());
        System.out.println("appleNameList:"+appleNameList);

        //過濾名字為蘋果的元素
        List<Apple> appleList1 = appleList.stream().filter(x -> x.getName().equals("蘋果1"))
                .collect(Collectors.toList());
        System.out.println("appleList1:"+appleList1);

        //取前兩位元素
        List<Apple> limitList = appleList.stream().limit(2).collect(Collectors.toList());
        System.out.println("limitList:"+limitList);

        //取后兩位元素
        List<Apple> skipList = appleList.stream().skip(2).collect(Collectors.toList());
        System.out.println("skipList:"+skipList);

        //取第三位元素
        List<Apple> collectList = appleList.stream().limit(3).skip(2).collect(Collectors.toList());
        System.out.println("collectList:"+collectList);

排序(升序、降序、多條件排序):

//返回 對象集合以UsergetAge升序排序:年齡   --默認升序
        userList.stream().sorted(Comparator.comparing(User::getAge));

        //返回 對象集合以UsergetAge降序排序  ===這里寫在前面 和寫在后面要看清楚,弄明白
        userList.stream().sorted(Comparator.comparing(User::getAge).reversed()); //排序結果后再排序,
        userList.stream().sorted(Comparator.comparing(User::getAge, Comparator.reverseOrder()));//是直接進行排序

        //返回 對象集合以UsergetAge升序排序:**年齡並返回前n個元素**  --默認升序  ==下面同樣寫法
        userList.stream().sorted(Comparator.comparing(User::getAge)).limit(2);

        //返回 對象集合以UsergetAge升序排序:**年齡並去除前 n 個元素**  --默認升序 ==下面同樣寫法
        userList.stream().sorted(Comparator.comparing(User::getAge)).skip(2);

        //返回 對象集合以UsergetAge升序 getFraction升序
        userList.stream().sorted(Comparator.comparing(User::getAge).thenComparing(User::getFraction));

        //先以getAge升序,升序結果進行getAge降序,再進行getFraction升序
        userList.stream().sorted(Comparator.comparing(User::getAge).reversed().thenComparing(User::getFraction));

        //先以getAge降序,再進行getFraction升序
        userList.stream().sorted(Comparator.comparing(User::getAge, Comparator.reverseOrder()).thenComparing(User::getFraction));

        //先以getAge升序,升序結果進行getAge降序,再進行getFraction降序
        userList.stream().sorted(Comparator.comparing(User::getAge).reversed().thenComparing(User::getFraction, Comparator.reverseOrder()));

        //先以getAge降序,再進行getFraction降序
        userList.stream().sorted(Comparator.comparing(User::getAge, Comparator.reverseOrder()).thenComparing(User::getFraction, Comparator.reverseOrder()));

        //先以getAge升序,升序結果進行getAge降序,再進行getFraction升序,結果進行getAge降序getFraction降序
        userList.stream().sorted(Comparator.comparing(User::getAge).reversed().thenComparing(User::getFraction).reversed());

        //先以getAge升序,再進行getFraction降序
        userList.stream().sorted(Comparator.comparing(User::getAge).thenComparing(User::getFraction, Comparator.reverseOrder()));

取交集、差集、並集:

 // 交集
        List<String> intersection = list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList());
        System.out.println("---得到交集 intersection---");//333 111
        intersection.parallelStream().forEach(System.out :: println);

        // 差集 (list1 - list2)
        List<String> reduce1 = list1.stream().filter(item -> !list2.contains(item)).collect(Collectors.toList());
        System.out.println("---得到差集 reduce1 (list1 - list2)---");//222
        reduce1.parallelStream().forEach(System.out :: println);

        // 差集 (list2 - list1)
        List<String> reduce2 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
        System.out.println("---得到差集 reduce2 (list2 - list1)---");//444
        reduce2.parallelStream().forEach(System.out :: println);

        // 並集
        List<String> listAll = list1.parallelStream().collect(Collectors.toList());
        List<String> listAll2 = list2.parallelStream().collect(Collectors.toList());
        listAll.addAll(listAll2);
        System.out.println("---得到並集 listAll---");//111 222 333 111 333 444
        listAll.parallelStream().forEach(System.out :: println);

        // 去重並集
        List<String> listAllDistinct = listAll.stream().distinct().collect(Collectors.toList());
        System.out.println("---得到去重並集 listAllDistinct---");//111 222 333 444
        listAllDistinct.parallelStream().forEach(System.out :: println);

        // 去重並集
        Set<String> set = listAll.stream().collect(Collectors.toSet());
        System.out.println("---得到去重並集 set---");//111 222 333 444
        set.parallelStream().forEach(System.out :: println);

        System.out.println("---原來的List1---");//111 222 333
        list1.parallelStream().forEach(System.out :: println);
        System.out.println("---原來的List2---");//111 333 444
        list2.parallelStream().forEach(System.out :: println);

鳴謝:

https://www.cnblogs.com/john8169/p/9780524.html

https://www.cnblogs.com/miaoying/p/13042091.html 

https://blog.csdn.net/gzt19881123/article/details/78327465/

               

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM