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

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章