Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 - stream convert map's value type

Tags:

java

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().

like image 316
J.Done Avatar asked Jun 14 '17 07:06

J.Done


People also ask

How do I convert a map value to a List?

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.

Which method is used to convert the elements of a stream to a single value?

Stream can be converted into Set using forEach(). Loop through all elements of the stream using forEach() method and then use set.

What are the types of streams in Java 8?

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.

What are two types of streams in Java 8?

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.


1 Answers

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
        );
like image 59
Alberto S. Avatar answered Sep 22 '22 02:09

Alberto S.