![](/img/trans.png)
[英]Java 8 Lambdas flatmapping, groupingBy and mapping to get a Map of T and List<K>
[英]Mapping a list to Map Java 8 stream and groupingBy
我有这个简单的Bean类:
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;
}
}
在我的主要课程中,我向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);
现在我想将图书列表转换为此表单的地图:
Map<String, List<String>>
这样输出(上图)就像:
//isbn: value1, value2
1234: author1, author2
5678: author1
因此,我需要将isbn作为关键字和作者作为值进行分组。 一个isbn可以有多个作者。
我想尝试如下:
Map<String, List<String>> library = books.stream().collect(Collectors.groupingBy(Book::getAttribute));
bean的格式无法更改。 如果bean有字符串值而不是map,我可以做到,但坚持使用地图。
我已经编写了传统的java 6/7正确的方法,但尝试通过Java 8新功能来实现。 感谢帮助。
你可以这样做:
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>>
。 从那里,您可以按条目键对元素进行分组,并将每个条目映射到您收集到值的List中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.