Java stream reduce

后端 未结 4 2487
南旧
南旧 2021-02-20 11:53

I have the following example data set that I want to transform / reduce using Java stream api based on direction\'s value

Direction    int[]
IN           1, 2
O         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-20 12:39

    I think your solution is pretty nice already, especially as using a reduction enables parallelism easily compared to collecting into a shared outside container. But it's easier to use collect instead of reduce as Holger pointed out. Furthermore, the conditions in the accumulator can be simplified a bit, and you forgot to merge the last and first elements in the combiner:

    List reduce = tupleStream.collect(ArrayList::new, WDParser::add, WDParser::combine);
    
    private static List combine(List list1, List list2)
    {
        if (!list2.isEmpty())
        {
            add(list1, list2.remove(0)); // merge lists in the middle if necessary
            list1.addAll(list2);         // add all the rest
        }
        return list1;
    }
    
    private static List add(List list, Tuple t)
    {
        int lastIndex = list.size() - 1;
        if (list.isEmpty() || list.get(lastIndex).getDirection() != t.getDirection())
        {
            list.add(t);
        }
        else
        {
            list.set(lastIndex, list.get(lastIndex).merge(t));
        }
        return list;
    }
    

    Instead of using indexes to access the first/last element you could even use LinkedList and the methods add/removeFirst/Last().

提交回复
热议问题