Java 8 从一对多分组

Java 8 grouping by from one-to-many(Java 8 从一对多分组)
本文介绍了Java 8 从一对多分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想学习如何将 Java 8 语法与流一起使用,但有点卡住了.

I want to learn how to use the Java 8 syntax with streams and got a bit stuck.

如果每个值都有一个键,那么 groupingBy 就很容易了.但是,如果我对每个值都有一个键列表并且仍然想用 groupingBy 对它们进行分类怎么办?我是否必须将其分解为多个语句,或者是否可以使用一些流魔术来使其更简单.

It's easy enough to groupingBy when you have one key for every value. But what if I have a List of keys for every value and still want to categorise them with groupingBy? Do I have to break it into several statements or is there possibly a little stream magic that can be done to make it simpler.

这是基本代码:

List<Album> albums = new ArrayList<>();
Map<Artist, List<Album>> map = albums.stream().collect(Collectors.groupingBy(this::getArtist));

如果每张专辑只有一位艺术家,效果会很好.但我必须返回一个列表,因为一个专辑可以有很多艺术家.专辑和艺术家当然是用来说明的,我有真实世界的类型..

It works great if there is only one Artist for every Album. But I must return a List since an Album can have many Artists. Album and Artist are used for illustration of course, I have real-world types..

可能有一个简单的解决方案,但我有一段时间没有找到它,所以我呼吁这个网站所代表的集体大脑来解决它.:) 如果不存在简单的解决方案,也欢迎使用复杂的解决方案.

There's probably a simple solution but I haven't found it in a while so I'm calling on the collective brain this site represents to solve it. :) A complex solution is also welcome in case a simple one doesn't exist.

在 Album 类中或作为以 Album 作为参数的实用方法:

In Album class or as an utility method taking an Album as argument:

Artist getArtist(); // ok

List<Artist> getArtist(); // Not ok, since we now have many "keys" for every Album

干杯,迈克尔·格雷夫

推荐答案

我想你是在 Collectors.mapping 之后,它可以作为第二个参数传递给 groupingBy

I think you are after Collectors.mapping which can be passed as a second argument to groupingBy

完整示例

import java.util.AbstractMap;
import java.util.List;
import java.util.Map;

import static java.util.Arrays.asList;
import static java.util.Map.Entry;
import static java.util.stream.Collectors.*;

public class SO {

    public static void main(String... args) {

        List<Album> albums = asList(
                new Album(
                        asList(
                                new Artist("bob"),
                                new Artist("tom")
                        )
                ),
                new Album(asList(new Artist("bill")))
        );

        Map<Artist, List<Album>> x = albums.stream()
                .flatMap(album -> album.getArtist().stream().map(artist -> pair(artist, album)))
                .collect(groupingBy(Entry::getKey, mapping(Entry::getValue, toList())));

        x.entrySet().stream().forEach(System.out::println);
    }

    static class Artist {
        private final String name;

        Artist(String name) {
            this.name = name;
        }

        public String toString() {return name;}

    }

    static class Album {
        private List<Artist> artist;

        Album(List<Artist> artist) {
            this.artist = artist;
        }

        List<Artist> getArtist() {
            return artist;
        }

    }

    private static <T,U> AbstractMap.SimpleEntry<T,U> pair(T t, U u) {
        return new AbstractMap.SimpleEntry<T,U>(t,u);
    }


}

这篇关于Java 8 从一对多分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)