如何从可以属于两个或多个组的列表中对对象进行分组? [英] How to group objects from a list which can belong to two or more groups?

查看:68
本文介绍了如何从可以属于两个或多个组的列表中对对象进行分组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目列表,其中每个项目都可以属于一个或多个类别.对于一组有限的category(string),我想创建一个类别为键,Items列表为值的地图.

I have a list of Items where each Item can belong to one or more category. For a limited set of categories(string) I want to create a map with category as key and list of Items as value.

假设我的Item类的定义如下所示:

Assume my Item class is defined as shown below:

public static class Item{
    long id;
    List<String> belongsToCategories;

    public List<String> getBelongsToCategories() {
        return belongsToCategories;
    }

    public void setBelongsToCategories(List<String> belongsToCategories) {
        this.belongsToCategories = belongsToCategories;
    }

    public Item(long id,List<String> belongsToCategories) {
        this.id = id;
        this.belongsToCategories = belongsToCategories;
    } 

    @Override
    public String toString() {
        return "Item{" + "id=" + id + '}';
    }        
}

和项目列表:

public static void main(String[] args) {
    List<Item> myItemList   = new ArrayList<>();

    myItemList.add(new Item(1,Arrays.asList("A","B")));
    myItemList.add(new Item(2,Arrays.asList("A","C")));
    myItemList.add(new Item(3,Arrays.asList("B","C")));
    myItemList.add(new Item(4,Arrays.asList("D")));
    myItemList.add(new Item(5,Arrays.asList("D","E")));
    myItemList.add(new Item(6,Arrays.asList("A","F")));

    Map<String,List<Item>> myMap= new HashMap<>();

如何从myList填充myMap?

How can i fill myMap from myList?

我认为Stream API可以提供帮助,但是当某项可以属于一个或多个类别时,我不知道将哪个分类器放入groupingBy方法中

I thought Stream API could help, but I don't know which classifier to put in the groupingBy method when an Item can belong to one or more categories

 myItemList.stream().collect(Collectors.groupingBy(classifier));

myItemList.stream().collect(Collectors.groupingBy(Item::getBelongsToCategories));

产生

[D, E]=[Item{id=5}]
[B, C]=[Item{id=3}]
[A, B]=[Item{id=1}]
[D]=[Item{id=4}]
[A, C]=[Item{id=2}]
[A, F]=[Item{id=6}]

预期很难,例如:

A=[Item{id=1}, Item{id=2}, Item{id=6}]
B=[Item{id=1}, Item{id=3}]
C=[Item{id=2}, Item{id=3}]
D=[Item{id=4}, Item{id=5}]
E=[Item{id=5}]
F=[Item{id=6}]

推荐答案

您可以使用flatMap映射到SimpleEntry,然后将groupingBy映射为:

You can use flatMap to map to SimpleEntry and then groupingBy as :

return items.stream()
        .flatMap(p -> p.getBelongsToCategories()
                .stream()
                .map(l -> new AbstractMap.SimpleEntry<>(l, p)))
        .collect(Collectors.groupingBy(Map.Entry::getKey,
                Collectors.mapping(Map.Entry::getValue,
                        Collectors.toList())));

这篇关于如何从可以属于两个或多个组的列表中对对象进行分组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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