-3

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"). 
Tunaki
  • 132,869
  • 46
  • 340
  • 423
NHS
  • 195
  • 1
  • 2
  • 13
  • 1
    List has a single generic type. List does not exist. Post code that makes sense, and compiles. Also, please respect the basic Java naming conventions. Variables start with a lowercase letter. – JB Nizet Jun 18 '16 at 13:05
  • Thanks for altering me, i replaced the Map by List. edited and corrected the question. – NHS Jun 18 '16 at 13:14
  • 1
    Still doesn't compile (add() takes a single argument, not 3), and still doesn't respect the naming conventions. Take a step back, open your IDE, write code that compiles in the IDE, and then fix your question. – JB Nizet Jun 18 '16 at 13:20
  • 2
    Furthermore you need some explicit casts, since you are dealing with `Object[]` arrays, you cannot expect a typed `Map`. Besides from that, I guess you'd better off using the `toMap` collector, with a custom merger that will either return the previous or new value encountered (assuming a same id is always mapped to the same employee value), instead of `groupingBy`. – Alexis C. Jun 18 '16 at 13:25
  • 1
    I think you can refer to http://stackoverflow.com/questions/32312876/ignore-duplicates-when-producing-map-using-streams – Tunaki Jun 18 '16 at 14:08
  • @AlexisC. It works with me. but don't know how to accept your answer in a comment. – NHS Jun 18 '16 at 14:12

1 Answers1

7

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}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255