Why no tail() or head() method in List to get last or first element?

前端 未结 8 920
死守一世寂寞
死守一世寂寞 2020-12-29 04:45

I recently had a discussion with a collegue why the List interface in Java doesn\'t have a head() and tail() method.

In order to implement

8条回答
  •  清歌不尽
    2020-12-29 05:29

    If you want to process a list recursively, which is often what head/tail are used for in functional programming, you can use an Iterator.

    Integer min(Iterator iterator) {
        if ( !iterator.hasNext() ) return null;
        Integer head = iterator.next();
        Integer minTail = min(iterator);
        return minTail == null ? head : Math.min(head, minTail);
    }
    

提交回复
热议问题