天天看點

Java flatMap 轉化 嵌套list 為Map

實體

public class Group {
    private String salesTeam;
    private String salesTeamId;
    private List<String> provinces;
    private List<String> childGroups;
    }
    
           

實作效果

List<Group> 轉化為 
Map<String,Group> childGroupsMap;

其中key 是 childGroups清單。
           

使用flatMap

Map<String, Group> childGroupsMap = childGroups.stream()
            .flatMap(a -> a.getChildGroups().stream().map(listItem -> new AbstractMap.SimpleEntry<>(listItem, a)))
            .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));