Java 8 Stream分组而不返回List

时间:2016-06-18 13:02:34

标签: java java-8 java-stream

有没有办法直接从Java 8中的Map<Long, String>函数创建groupingBy,而不是创建Map<Long, Set<String>>

我有以下代码:

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

我需要o / p之类的:

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

1 个答案:

答案 0 :(得分:3)

你需要的只是toMap(),它有一个合并函数,它保存当前的员工名称(或新的名字,因为它们应该相等):

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}