List display to display Java 8 stream and grouping By

I have this simple Bean class:

public class Book { public Book(Map<String, String> attribute) { super(); this.attribute = attribute; } //key is isbn, val is author private Map<String, String> attribute; public Map<String, String> getAttribute() { return attribute; } public void setAttribute(Map<String, String> attribute) { this.attribute = attribute; } } 

In my main class, I added some information to the List:

  Map<String, String> book1Details = new HashMap<String, String>(); book1Details.put("1234", "author1"); book1Details.put("5678", "author2"); Book book1 = new Book(book1Details); Map<String, String> book2Details = new HashMap<String, String>(); book2Details.put("1234", "author2"); Book book2 = new Book(book2Details); List<Book> books = new ArrayList<Book>(); books.add(book1); books.add(book2); 

Now I want to convert the list of books to a map of this form:

 Map<String, List<String>> 

So, the output (map above) looks like this:

 //isbn: value1, value2 1234: author1, author2 5678: author1 

So, I need to group the entries using isbn as the key and authors as the values. One isbn may have several authors.

I am trying as shown below:

 Map<String, List<String>> library = books.stream().collect(Collectors.groupingBy(Book::getAttribute)); 

Bean format cannot be changed. If the Bean has string values ​​instead of a map, I can do this, but am stuck with the map.

I wrote a traditional java 6/7 way to do it right, but tried to do it through Java 8 new features. Appreciate the help.

+7
java collections lambda java-8
source share
1 answer

You can do it as follows:

 Map<String, List<String>> library = books.stream() .flatMap(b -> b.getAttribute().entrySet().stream()) .collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList()))); 

From Stream<Book> , you closely match it with the stream of each displayed map so that you have Stream<Entry<String, String>> . From there, you group items by record keys and map each record to its value, which you put together in a list for the values.

+9
source share

All Articles