Java 8 - stream conversion conversion type
I would like to convert the type List<A>
to List<B>
. can i do it with java 8 stream method?
Map< String, List<B>> bMap = aMap.entrySet().stream().map( entry -> {
List<B> BList = new ArrayList<B>();
List<A> sList = entry.getValue();
// convert A to B
return ???; Map( entry.getKey(), BList) need to return
}).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
I tried with this code, but couldn't convert it inside map ().
source to share
You can instantiate AbstractMap.simpleEntry
in a function map
and perform the conversion.
eg. the following code converts List<Integer>
to List<String>
:
Map<String, List<Integer>> map = new HashMap<>();
Map<String, List<String>> transformedMap = map.entrySet()
.stream()
.map(e -> new AbstractMap.SimpleEntry<String, List<String>>(e.getKey(), e.getValue().stream().map(en -> String.valueOf(en)).collect(Collectors.toList())))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
source to share
If I understood correctly, you have it Map<String, List<A>>
, and you want to convert it to Map<String, List<B>>
. You can do something like:
Map<String, List<B>> result = aMap.entrySet().stream()
.collect(Collectors.toMap(
entry -> entry.getKey(), // Preserve key
entry -> entry.getValue().stream() // Take all values
.map(aItem -> mapToBItem(aItem)) // map to B type
.collect(Collectors.toList()) // collect as list
);
source to share
You can do it like this:
public class Sandbox {
public static void main(String[] args) {
Map<String, List<A>> aMap = null;
Map<String, List<B>> bMap = aMap.entrySet().stream().collect(toMap(
Map.Entry::getKey,
entry -> entry.getValue().stream()
.map(Sandbox::toB)
.collect(toList())));
}
private static B toB(A a) {
// add your conversion
return null;
}
class B {}
class A {}
}
source to share