Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

java - Inserting Map into Map using streams

I'd like to know how I can insert a map into another map using streams in java.

I have a two maps

    Map<String, List<Character>> map1

    Map<String, List<Integer>> map2

I d like to merge both maps such that we have

    Map<String, Map<Character, Integer>> finalmap

if map1 is something like

    {String1 = [Character1, Character2], String2 = [Character3, Character4], etc}

and map2 is

    {String1 = [Integer1, Integer2], String2 = [Integer3, Integer4], etc}

I want it to merge such that the innermap maps Character1 with Integer1 and so on. Does someone have an idea how to solve this problem? :)

question from:https://stackoverflow.com/questions/65857568/inserting-map-into-map-using-streams

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Map<String, Map<Character, Integer>> map3 = map1.entrySet()
                .stream()
                .flatMap(entry -> {
                    if (map2.containsKey(entry.getKey())) {
                        List<Integer> integers = map2.get(entry.getKey());
                        List<Character> characters = entry.getValue();
                        Map<Character, Integer> innerMap = IntStream.range(0, Math.min(integers.size(), characters.size()))
                                .mapToObj(i -> Map.entry(characters.get(i), integers.get(i)))
                                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

                        return Stream.of(Map.entry(entry.getKey(), innerMap));
                    }

                    return Stream.empty();
                })
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...