grouping objects java 8

前端 未结 3 1997
鱼传尺愫
鱼传尺愫 2021-01-13 09:56

I have something like the below :

public class MyClass {
private Long stackId
private Long questionId
}

A collection of say 100, where the

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-13 10:36

    List inputs = Arrays.asList(
        new MyClass(1L, 100L),
        new MyClass(1L, 101L),
        new MyClass(1L, 102L),
        new MyClass(1L, 103L),
        new MyClass(2L, 200L),
        new MyClass(2L, 201L),
        new MyClass(2L, 202L),
        new MyClass(2L, 203L)
    );
    
    Map> result = inputs
        .stream()
        .collect(
          Collectors.groupingBy(MyClass::getStackId,
            Collectors.mapping(
              MyClass::getQuestionId, 
              Collectors.toList()
            )
          )
        );
    

提交回复
热议问题