Java – creates a map from a list, where the key is part of the internal and external objects
•
Java
Is it possible (in a simple way) to change it to java8 stream? (please don't comment / answer, if you want to tell me two better, instead of all loops should be changed to flow, this is not a point)
final Map<String,String> map = new HashMap<>(); for(final Person person: list) { for(final Internal internal: person.getInternals()) { final String key = person.getName() + internal.getKey(); map.put(key,internal.getValue()); } }
The main problem is that I can't use flatmap because I will lose my previous information Each created key is unique
Solution
Then you can pass them through a pair (although I didn't compile it, the idea should be there)
list.stream() .flatMap(person -> person.getInternals() .stream() .map(internal -> Pair.of(person.getName() + internal.getKey(),internal.getValue())) .collect(Collectors.toMap(Pair::getLeft,Pair::getRight));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码