grouping objects java 8

前端 未结 3 1999
鱼传尺愫
鱼传尺愫 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:38

    You can use the java8 groupingBy collector. Like this:

    import org.junit.Test;
    
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Set;
    import java.util.stream.Collectors;
    
    public class RandomTest {
    
        class MyClass {
            private Long stackId;
            private Long questionId;
    
            public MyClass(Long stackId, Long questionId) {
                this.stackId = stackId;
                this.questionId = questionId;
            }
    
            public Long getStackId() {
                return stackId;
            }
    
            public Long getQuestionId() {
                return questionId;
            }
        }
    
        public class MyOtherClass {
            private Long stackId;
            private Set questionIds;
    
            public MyOtherClass(Long stackId, Set questionIds) {
                this.stackId = stackId;
                this.questionIds = questionIds;
            }
    
            public Long getStackId() {
                return stackId;
            }
    
            public Set getQuestionIds() {
                return questionIds;
            }
        }
    
        @Test
        public void test() {
            List classes = new ArrayList<>();
            List otherClasses = new ArrayList<>();
    
            //populate the classes list
            for (int j = 1; j <= 25; j++) {
                for (int i = 0; i < 4; i++) {
                    classes.add(new MyClass(0L + j, (100L*j) + i));
                }
            }
    
            //populate the otherClasses List
            classes.stream().collect(Collectors
                    .groupingBy(MyClass::getStackId, Collectors.mapping(MyClass::getQuestionId, Collectors.toSet())))
                    .entrySet().stream().forEach(
                    longSetEntry -> otherClasses.add(new MyOtherClass(longSetEntry.getKey(), longSetEntry.getValue())));
    
            //print the otherClasses list
            otherClasses.forEach(myOtherClass -> {
                System.out.print(myOtherClass.getStackId() + ": [");
                myOtherClass.getQuestionIds().forEach(questionId-> System.out.print(questionId + ","));
                System.out.println("]");
            });
        }
    }
    

提交回复
热议问题