Mango Mango - 11 months ago 100
Java Question

Java 8 Stream groupingby without returning List

Is there a way to create

Map<Long, String>
directly from a
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"};

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

I need the o/p like:

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


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 =
        .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}