merge objects using java8

This question already has an answer here:

  • Group a list of objects by an attribute : Java

    8 answers

I have a list like this

    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);

where Objecto is an object of this type

class Objeto{
private String contentId;
private String address;

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

//Getters and Setters

}

I want to merge the list into a HashMap like this

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

Can I use a java 8 lambda to achieve it? Or though any other way?

Many thanks!

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(","))));
}
}

Output:

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

You can use Collectors.groupingBy to group your objects by their IDs and Collectors.mapping to map each Objeto to its corresponding address:

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