JDK8 flatmap函式

Allen_Hao發表於2024-03-26

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class A {
    private String name;
    private String xuehao;

    public A(String name, String xuehao) {
        this.name = name;
        this.xuehao = xuehao;
    }

    public String getName() {
        return name;
    }

    public String getXuehao() {
        return xuehao;
    }
}

public class Main {
    public static void main(String[] args) {
        List<AA> list = Arrays.asList(new AA("Tom", "12"), new AA("Allen", "34"),new AA("Kity","888"));

        Map<Integer, List<String>> map = list.stream()
                .flatMap(a -> Stream.of(new AbstractMap.SimpleEntry<>(1, a.getName()), new AbstractMap.SimpleEntry<>(2, a.getXuehao())))
                .collect(Collectors.groupingBy(Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList())));

        System.out.println(map);
    }
}

{1=[Tom, Allen, Kity], 2=[12, 34, 888]}

相關文章