• Collectors.groupingBy、Collectors.mapping......等的使用


    1.Collectors.groupingBy、Collectors.mapping:

    参考博客:https://blog.csdn.net/L_fly_J/article/details/120164362

    Person.java:

    package com.mayikt.entity;
    
    public class Person {
        private String name;
        private int age;
    
        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }
        public String getName() {
            return name;
        }
        public int getAge() {
            return age;
        }
    }
    View Code

    测试代码:

    package com.mayikt.stream;
    
    import com.mayikt.entity.Person;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.stream.Collectors;
    
    public class TestCollectorsMapping {
        public static void main(String[] args) {
            List<Person> list = new ArrayList<>();
            list.add(new Person("Ram", 30));
            list.add(new Person("Shyam", 20));
            list.add(new Person("Shiv", 20));
            list.add(new Person("Mahesh", 30));
    
            String nameByAge = list.stream().collect(Collectors.mapping(Person::getName, Collectors.joining(",", "[", "]")));
            System.out.println(nameByAge);
            nameByAge = list.stream().map(person -> person.getName()).collect(Collectors.joining(",", "[", "]"));
            System.out.println(nameByAge);
    
            Map<Integer, String> nameByAgeMap = list.stream().collect(
                    Collectors.groupingBy(Person::getAge, Collectors.mapping(Person::getName, Collectors.joining(",", "[", "]"))));
            nameByAgeMap.forEach((k, v) -> System.out.println("Age:" + k + "  Persons: " + v));
    
            Map<Integer, List<String>> map2 = list.stream().collect(
                    Collectors.groupingBy(Person::getAge, Collectors.mapping(Person::getName, Collectors.toList())));
            System.out.println(map2);
        }
    }
    [Ram,Shyam,Shiv,Mahesh]
    [Ram,Shyam,Shiv,Mahesh]
    可以发现达到相同的效果
    
    Age:20  Persons: [Shyam,Shiv]
    Age:30  Persons: [Ram,Mahesh]
    封装为Map后返回
    
    {20=[Shyam, Shiv], 30=[Ram, Mahesh]}
  • 相关阅读:
    浏览器的跨域请求 与 CORS(跨域资源共享)
    HTML 占位符
    C# 中的 base和this
    推荐一个pdf引擎
    整理wifi相关的知识点
    交叉编译(ISC)DHCP:dhcp-4.3.0b1
    (转载)子网掩码,网关的概念
    海思-VB被占用导致vb无法去初始化
    c++创建文件时重命名同名文件
    iw创建虚拟网卡wlan1,ap_sta共存
  • 原文地址:https://www.cnblogs.com/tenWood/p/16160501.html
Copyright © 2020-2023  润新知