Iterate twice on values (MapReduce)

前端 未结 11 1075
轮回少年
轮回少年 2020-11-29 07:22

I receive an iterator as argument and I would like to iterate on values twice.

public void reduce(Pair key, Iterator          


        
11条回答
  •  迷失自我
    2020-11-29 08:15

    If method signature cannot be changed then I would suggest using Apache Commons IteratorUtils to convert Iterator to ListIterator. Consider this example method for iterating twice on values:

    void iterateTwice(Iterator it) {
        ListIterator lit = IteratorUtils.toListIterator(it);
        System.out.println("Using ListIterator 1st pass");
        while(lit.hasNext())
            System.out.println(lit.next());
    
        // move the list iterator back to start
        while(lit.hasPrevious())
            lit.previous();
    
        System.out.println("Using ListIterator 2nd pass");
        while(lit.hasNext())
            System.out.println(lit.next());
    }
    

    Using code like above I was able to iterate over the list of values without saving a copy of List elements in my code.

提交回复
热议问题