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 从一对多分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

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

相关文档推荐

Sending a keyboard event from java to any application (on-screen-keyboard)(将键盘事件从 java 发送到任何应用程序(屏幕键盘))
How to make JComboBox selected item not changed when scrolling through its popuplist using keyboard(使用键盘滚动其弹出列表时如何使 JComboBox 所选项目不更改)
Capturing keystrokes without focus(在没有焦点的情况下捕获击键)
How can I position a layout right above the android on-screen keyboard?(如何将布局放置在 android 屏幕键盘的正上方?)
How to check for key being held down on startup in Java(如何检查在Java中启动时按住的键)
Android - Get keyboard key press(Android - 获取键盘按键)