使用java8合并对象

时间:2017-08-24 11:01:06

标签: java lambda java-8

我有一个像这样的列表

    List<Objeto> myList = new ArrayList<Objeto>();
    Objeto o1 = new Objeto("1", "bbb");
    myList.add(o1);
    Objeto o2 = new Objeto("1", "rrrr");
    myList.add(o2);
    Objeto o3 = new Objeto("2", "eee");
    myList.add(o3);
    Objeto o4 = new Objeto("2", "wwww");
    myList.add(o4);
    Objeto o5 = new Objeto("3", "iiii");
    myList.add(o5);

其中Objecto是此类型的对象

class Objeto{
private String contentId;
private String address;

Objeto(String id, String address){
    this.contentId = id;
    this.address = address;
}

// Getters and Setters

}

我想将列表合并到像这样的HashMap中

(1, {"bbb","rrrr"})
(2, {"eee","wwww"})
(3, {"iiii"})

我可以使用java 8 lambda来实现它吗?或者通过其他任何方式?

非常感谢!

2 个答案:

答案 0 :(得分:4)

您可以使用Collectors.groupingBy按ID分组对象,Collectors.mapping将每个Objeto映射到相应的地址:

Map<String,List<String>>
    map = myList.stream()
                .collect(Collectors.groupingBy(Objeto::getContentID,
                                               Collectors.mapping(Object::getAddress
                                                                  Collectors.toList())));

答案 1 :(得分:2)

package com.company;

import java.util.ArrayList;
import java.util.stream.Collectors;

public class Main {
public static class Objeto {
    private String contentId;
    private String address;

    Objeto(String id, String address) {
        this.contentId = id;
        this.address = address;
    }

    public String getContentId() {
        return contentId;
    }

    public String getAddress() {
        return address;
    }
}

public static void main(String[] args) {
    java.util.List<Objeto> myList = new ArrayList<Objeto>();
    Objeto o1 = new Objeto("1", "bbb");
    myList.add(o1);
    Objeto o2 = new Objeto("1", "rrrr");
    myList.add(o2);
    Objeto o3 = new Objeto("2", "eee");
    myList.add(o3);
    Objeto o4 = new Objeto("2", "wwww");
    myList.add(o4);
    Objeto o5 = new Objeto("3", "iiii");
    myList.add(o5);

    myList.stream().collect(
            Collectors.groupingBy(
                    Objeto::getContentId,
                    Collectors.mapping(
                            Objeto::getAddress,
                            Collectors.toList()))
    ).forEach((id, addresses) -> System.out.printf("(%s, {%s})\n", id, addresses.stream().collect(Collectors.joining(","))));
}
}

输出:

(1, {bbb,rrrr})
(2, {eee,wwww})
(3, {iiii})