java8--- List、toMap、數組互轉、分組(groupingBy、Collectors.toMap)、去重


 

 

  

{ "code1":{"id":"11","name":"n11"}, "code2":{"id":"12","name":"n12"} }

Map<String, String> idNoMap = tItems.stream().collect(Collectors.toMap(TItem::getItemId, TItem::getItemNo, (o, n) -> o, LinkedHashMap::new));
Map<String, SaleSkuVO> skuByItemNoMap = skus.stream().collect(Collectors.toMap(SaleSkuVO::getItemNo, p -> p, (o, n) -> o));
Map<String, SaleSkuVO> skuByItemNoMap = skus.stream().collect(Collectors.toMap(SaleSkuVO::getItemNo + "_" + SaleSkuVO::getItemName, p -> p, (o, n) -> o));

Map<String, List<SaleSkuVO>> skuByItemNoMapList = skus.stream().collect(Collectors.groupingBy(SaleSkuVO::getItemNo));

{ "code1":[ {"id":"11","name":"n11","code":"code1"}, {"id":"21","name":"n21","code":"code1"} ], "code2":[ {"id":"12","name":"n12","code":"code2"}, {"id":"22","name":"n22","code":"code2"} ] }

 

 

 

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

 

 

 

 

 

https://zacard.net/2016/03/17/java8-list-to-map/
重復key的情況
代碼如下:

public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity()));
}
這個方法可能報錯(java.lang.IllegalStateException: Duplicate key),因為name是有可能重復的。toMap有個重載方法,可以傳入一個合並的函數來解決key沖突問題:

public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}
這里只是簡單的使用后者覆蓋前者來解決key重復問題。

指定具體收集的map
toMap還有另一個重載方法,可以指定一個Map的具體實現,來收集數據:

public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2, LinkedHashMap::new));
}

 

TreeMap<String, List<User>> treeMap = userList.stream()
                .sorted((o1, o2) -> o1.getAge() - o2.getAge())
                .collect(groupingBy(item -> item.getHeight, TreeMap::new, toList()));

 

 

// lambda優雅取出對象list中某個屬性重復的集合數據:
public class Test { // https://blog.csdn.net/qq_35902833/article/details/88351470
    @Data
    @AllArgsConstructor
    static class Dog {
        String name;
        int age;
    }
    public static List<Dog> dogs = null;
    static {
        dogs = new ArrayList<Dog>() {
            {
                add(new Dog("黃一", 11));
                add(new Dog("黃一", 22));
                add(new Dog("黃三", 33));
            }
        };
    }

    //@SuppressWarnings("AlibabaAvoidManuallyCreateThread")
    public static void main(String[] args) {

//        dogs.stream()
//                .flatMap(i->i.getSonList().stream()) // lambda:  list1.addAll(list2)
//                .collect(Collectors.toSet());

        Map<String, Long> collect = dogs.stream().
                collect(Collectors.groupingBy(i -> i.getName(), Collectors.counting()));
        System.out.println("-1-->" + collect.toString()); //-1-->{黃三=1, 黃一=2}

        Map<String, List<Dog>> collect1 = dogs.stream()
                .collect(Collectors.groupingBy(Dog::getName));
        System.out.println("-2-->" + collect1.toString());//-2-->{黃三=[test.Dog(name=黃三, age=33)], 黃一=[test.Dog(name=黃一, age=11), test.Dog(name=黃一, age=22)]}

        IntSummaryStatistics summaryStatistics3 = dogs.stream().collect(Collectors.summarizingInt(Dog::getAge));
        System.out.println("-3-->" + summaryStatistics3.getSum());//-3-->66

        Map<String, IntSummaryStatistics> intSummaryStatistics = dogs.stream().
                collect(Collectors.groupingBy(i -> i.getName(), Collectors.summarizingInt(Dog::getAge)));
        System.out.println("-4-->" + intSummaryStatistics);
        //-4-->{黃三=IntSummaryStatistics{count=1, sum=33, min=33, average=33.000000, max=33}, 黃一=IntSummaryStatistics{count=2, sum=33, min=11, average=16.500000, max=22}}
        System.out.println("-5-->" + intSummaryStatistics.get("黃一").getSum()); //-5-->33

IntSummaryStatistics collect21 = dogs.stream().collect(Collectors.summarizingInt(Dog::getAge)); Optional.ofNullable(collect21).ifPresent(System.out::println); //IntSummaryStatistics{count=3, sum=66, min=11, average=22.000000, max=33} System.out.println("-6-->" + Optional.ofNullable(collect21).get().getSum()); //-6-->66 List<String> collect7 = dogs.stream(). collect(Collectors.groupingBy(i -> i.getName(), Collectors.counting())) .entrySet() .stream() .map(entry -> { return "key-->" + entry.getKey() + "; val-->" + entry.getValue(); }) .collect(Collectors.toList()); System.out.println("-7-->" + collect7); //-7-->[key-->黃三; val-->1, key-->黃一; val-->2] List<String> collect8 = dogs.stream(). collect(Collectors.groupingBy(i -> i.getName(), Collectors.counting())) .entrySet() .stream() .filter(entry -> entry.getValue() > 1) .map(entry -> entry.getKey()) .collect(Collectors.toList()); System.out.println("-7-->" + collect8); //-7-->[黃一] Consumer<Dog> consumer = (dog) -> System.out.println("-8-->" + dog.getAge()); Predicate<Dog> dogPredicate = (dog) -> dog.getAge() > 10; Test.dogs.stream() .filter(dogPredicate) .limit(3) .forEach(consumer); //-8-->11 //-8-->22 //-8-->33 } }

 

 

// LIST、MAP、數組互轉、分組Collectors.groupingBy
public class CollectionMy {

    //出處:https://www.iteye.com/blog/bugyun-2433872
    public static void main(String[] args) {

        List<Person> listEntiyJapan = new ArrayList();
        listEntiyJapan.add(new Person(1, "ha1", 10));
        listEntiyJapan.add(new Person(2, "ha2", 11));
        listEntiyJapan.add(new Person(2, "ha3", 12));

//        String[] arrays = {"hello"," , ","world"};
//
//        System.out.println(arrayToList1(arrays));
//        System.out.println(arrayToList2(arrays));
//        System.out.println(listToArray1(arrayToList2(arrays)));
//        System.out.println(listToArray2(arrayToList2(arrays)));
//
//        listToMap1(listEntiyChina);
//        sortList(listEntiyJapan);
//
        listToMap4(listEntiyJapan);


        Map<String, Integer> mapRepeat = new HashMap<>();

    }


    //--------------進階-List轉為Map---------------------------------

    /**
     * Java8 List轉為Map
     * ID 必須為唯一性
     *
     * @param list
     * @return
     */
    public static void listToMap1(List<Person> list) {
        // list<bean> -> Map<String, String>
        //使用toMap方法的另一個變體來處理重復問題,它允許我們指定一個合並方法。這個合並方法允許用戶他們指定想如何處理多個值關聯到同一個鍵的沖突。
        //在下面展示的代碼中,我們只是使用了新的值,當然你也可以編寫一個智能的算法來處理沖突。
        Map<Integer, Person> mapp = list.stream().collect(Collectors.toMap(Person::getId, p -> p, (oldValue, newValue) -> newValue));
//      Map<Integer, Person> mapp = list.stream().collect(Collectors.toMap(Person::getId, Function.identity(),(oldValue, newValue) -> newValue));
        System.out.println("-10-->" + mapp);//-10-->{1=Person(id=1, name=ha1), 2=Person(id=2, name=ha2), 3=Person(id=3, name=ha3)}

        //可以通過使用toMap方法的第三個變體來指定其他的映射實現。這需要你指定將用來存儲結果的Map和Supplier。
        Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName, (oldValue, newValue) -> newValue, LinkedHashMap::new));
        Map<Integer, String> map01 = list.stream().collect(Collectors.toMap(item -> item.getId(), item -> item.getName(), (oldVal, currVal) -> oldVal + "-" + currVal));
        System.out.println("-11-->" + map);              //-12-->{1=ha1, 2=ha2, 3=ha3}
        System.out.println("-12-->" + map01.toString()); //-13-->{1=ha1, 2=ha2, 3=ha3-ha3}


    }

    /**
     * 分組
     * Java8 List轉為Map  Person -> Map<Integer, List<Person>>
     * 根據年齡排序后,再根據ID重復分組
     *
     * @param list
     * @return
     */
    public static Map<Integer, List<Person>> listToMap4(List<Person> list) {
        Collections.sort(list, Comparator.comparing(Person::getId).thenComparing(Person::getAge));
        list.forEach(System.out::println);
        Map<Integer, List<Person>> result = list.stream().collect(Collectors.groupingBy(Person::getId));
        System.out.println("--4---->" + result);

        //分組 演示
//      Map<Person, Long> collect41 = list.stream().collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
        Map<Person, Long> collect41 = list.stream().collect(Collectors.groupingBy(p -> p, Collectors.counting()));
        System.out.println("--41---->" + collect41);

        //1.3根據分組的key值對結果進行排序、放進另一個map中並輸出
        Map<Integer, Long> result1 = list.stream().collect(Collectors.groupingBy(Person::getId, Collectors.counting()));
        System.out.println("--42---->" + result1);// {1=1, 2=2}
        Map<String, Long> xMap = new HashMap<>();
        result1.entrySet().stream().sorted(Map.Entry.<Integer, Long>comparingByKey().reversed()) //reversed不生效
                .forEachOrdered(x -> xMap.put(x.getKey() + "", x.getValue()));
        System.out.println("--43---->" + xMap);// {1=1, 2=2}

        Map<Integer, Integer> result3 = list.stream().collect(
                Collectors.groupingBy(Person::getId, Collectors.summingInt(Person::getAge))
        );
        System.out.println("--44---->" + result3);//{1=10, 2=23}



        // 根據id去重  https://blog.csdn.net/lu930124/article/details/77595585/
        List<Person> unique = list.stream().collect(
                collectingAndThen(
                        toCollection(() -> new TreeSet<Person>(comparingLong(Person::getId))), ArrayList::new
                )
        );
        System.out.println("--45---->" + unique);//--45---->[Person(id=1, name=ha1, age=10), Person(id=2, name=ha2, age=11)]

        return result;
    }


    //----------------------------------基礎操作--------------

    /**
     * Java8 數組轉為List
     *
     * @param arrays
     * @return
     */
    public static List<String> arrayToList1(String[] arrays) {
        List<String> result = Stream.of(arrays).collect(Collectors.toList());
        return result;
    }


    /**
     * Java8 List轉為數組
     *
     * @param list
     * @return
     */
    public static String[] listToArray1(List<String> list) {
        String[] result = list.stream().toArray(String[]::new);
        Arrays.stream(result).forEach(str -> System.err.println(str));
        return result;
    }

    public static void sortList(List<Person> list) {
        Collections.sort(list, Comparator.comparing(Person::getId).thenComparing(Person::getAge));
        list.forEach(System.out::println);
    }

    public static List<String> arrayToList2(String[] arrays) {
        List<String> result = Arrays.asList(arrays);
        return result;
    }


    public static String[] listToArray2(List<String> list) {
        String[] result = list.toArray(new String[list.size()]);
        return result;
    }
}

 

Set<String> skusByItemNoSet = skus.stream().map(SaleSkuVO::getItemNo).collect(Collectors.toSet());
LinkedHashMap


免責聲明!

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



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