I have this simple Bean class:
public class Book { public Book(Map<String, String> attribute) { super(); 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:
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.
java collections lambda java-8
daman
source share