I would like to convert type List<A>
to List<B>
. can I do this 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 cannot convert it inside map().
Method 2: List ListofKeys = new ArrayList(map. keySet()); We can convert Map keys to a List of Values by passing a collection of map values generated by map. values() method to ArrayList constructor parameter.
Stream can be converted into Set using forEach(). Loop through all elements of the stream using forEach() method and then use set.
Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.
With Java 8, Collection interface has two methods to generate a Stream. stream() − Returns a sequential stream considering collection as its source. parallelStream() − Returns a parallel Stream considering collection as its source.
If I understood it correctly you have a Map<String, List<A>>
and you want to convert it to a 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
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With