3 ways to flatten a list of lists. Is there a reason to prefer one of them?

前端 未结 3 1139
孤独总比滥情好
孤独总比滥情好 2021-02-07 04:18

Assume we have a list as follows. CoreResult has a field of type List.

final List list = new LinkedList         


        
相关标签:
3条回答
  • 2021-02-07 04:48

    Option 3 and 2 is same, so up to you if you want to map first and then flat map or just flatmap.

    With option 1 you have to open another stream to perform further operations.

    0 讨论(0)
  • 2021-02-07 04:56

    I would go for option 2 or 3. If you want to flatten a List<List<Double>>, you would do this:

    List<Double> list = doubleList.stream()
                                  .flatMap(List::stream)
                                  .collect(Collectors.toList());
    
    0 讨论(0)
  • 2021-02-07 05:08

    I'm not sure about the performance of each one, but an important aspect of the builder pattern utilized by java streams is that it allows for readability. I personally find the option 2 to be the most readable. Option 3 is good, too. I would avoid option one because it kind of "cheats" the flattening of the collection.

    Put each method on its own line and determine which is the most intuitive to read. I rather like the second one:

    final List<Double> B = list.stream()
                               .map(CoreResult::getField)
                               .flatMap(Collection::stream)
                               .collect(Collectors.toList());
    
    0 讨论(0)
提交回复
热议问题