Why don't primitive Stream have collect(Collector)?

后端 未结 5 1378
-上瘾入骨i
-上瘾入骨i 2020-12-14 06:36

I\'m writing a library for novice programmers so I\'m trying to keep the API as clean as possible.

One of the things my Library needs to do is perform some complex c

5条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-14 07:01

    Perhaps if method references are used instead of lambdas, the code needed for the primitive stream collect will not seem as complicated.

    MyResult result = businessObjs.stream()
                                  .mapToInt( ... )
                                  .collect( 
                                      MyComplexComputationBuilder::new,
                                      MyComplexComputationBuilder::add,
                                      MyComplexComputationBuilder::merge)
                                  .build(); //prev collect returns Builder object
    

    In Brian's definitive answer to this question, he mentions two other Java collection frameworks that do have primitive collections that actually can be used with the collect method on primitive streams. I thought it might be useful to illustrate some examples of how to use the primitive containers in these frameworks with primitive streams. The code below will also work with a parallel stream.

    // Eclipse Collections
    List integers = Interval.oneTo(5).toList();
    
    Assert.assertEquals(
            IntInterval.oneTo(5),
            integers.stream()
                    .mapToInt(Integer::intValue)
                    .collect(IntArrayList::new, IntArrayList::add, IntArrayList::addAll));
    
    // Trove Collections
    
    Assert.assertEquals(
            new TIntArrayList(IntStream.range(1, 6).toArray()),
            integers.stream()
                    .mapToInt(Integer::intValue)
                    .collect(TIntArrayList::new, TIntArrayList::add, TIntArrayList::addAll));
    

    Note: I am a committer for Eclipse Collections.

提交回复
热议问题