将列表映射到Map Java 8流和分组 [英] Mapping a list to Map Java 8 stream and groupingBy

查看:79
本文介绍了将列表映射到Map Java 8流和分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个简单的Bean类:

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 have 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 books List to a map of this form:

Map<String, List<String>>

这样输出(上面的地图)就像:

So that the output (the map above) is like:

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

因此,我需要按isbn将条目分组为键,将作者作为值分组.一个isbn可以有多个作者.

So, I need to group the entries by isbn as key and authors as values. One isbn can have multiple authors.

我正在尝试如下操作:

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

bean的格式不能更改.如果bean具有字符串值而不是map,那么我可以做到,但是坚持使用map.

The format of the bean cannot be changed. If the bean had string values instead of map, I am able to do it, but stuck with the map.

我已经编写了正确的传统Java 6/7方法,但是尝试通过Java 8的新功能来实现.感谢帮助.

I have written the traditional java 6/7 way of doing it correctly, but trying to do it via Java 8 new features. Appreciate the help.

推荐答案

您可以这样做:

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

Stream<Book>中,使用它包含的每个映射的流对其进行平面映射,这样就可以拥有一个Stream<Entry<String, String>>.在这里,您可以按条目的键对元素进行分组,然后将每个条目映射到您收集到的值中的值.

From the Stream<Book>, you flat map it with the stream of each map it contains so that you have a Stream<Entry<String, String>>. From there you group the elements by the entries' key and map each entry to its value that you collect into a List for the values.

这篇关于将列表映射到Map Java 8流和分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆