Mango Mango - 5 months ago 42
Java Question

Java 8 Stream groupingby without returning List

Is there a way to create

Map<Long, String>
directly from a
groupingBy
function in Java 8, instead of creating
Map<Long, Set<String>>
?

I have the following code:

List<Object[]> list = new ArrayList<>();
//row[0] is the primary key and row[1] is the name of the employee
Object[] input1 = { 1l, "employee1", null};
Object[] input2 = { 1l, "employee1", "vorw2"};
Object[] input3 = { 2l, "employee2", "vorw3"};
Object[] input4 = { 3l, "employee3", "vorw1"};
list.add(input1);
list.add(input2);
list.add(input3);
list.add(input4);

//code to replaced
Map<String, Set<String>> byPK= list.stream().collect(Collectors.groupingBy(row -> row[0].longValue(), Collectors.mapping(row -> row[1].toString(),Collectors.toSet() )));


I need the o/p like:

List ==> (1l, "employee1" ), (2l,"employee2"), (3l, "employee3").

Answer

All you need is toMap(), with a merge function which keeps the current employee name (or the new one, since they should be equal):

Map<Long , String> employeeNamesById = 
    list.stream()
        .collect(Collectors.toMap(array -> (Long) array[0],
                                  array -> (String) array[1],
                                  (name1, name2) -> name1));
System.out.println("employeeNamesById = " + employeeNamesById);
// prints employeeNamesById = {1=employee1, 2=employee2, 3=employee3}
Comments