Why does Iterable not provide stream() and parallelStream() methods?

前端 未结 3 529
北海茫月
北海茫月 2020-11-28 17:56

I am wondering why the Iterable interface does not provide the stream() and parallelStream() methods. Consider the following class:

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 17:58

    If you know the size you could use java.util.Collection which provides the stream() method:

    public class Hand extends AbstractCollection {
       private final List list = new ArrayList<>();
       private final int capacity;
    
       //...
    
       @Override
       public Iterator iterator() {
           return list.iterator();
       }
    
       @Override
       public int size() {
          return list.size();
       }
    }
    

    And then:

    new Hand().stream().map(...)
    

    I faced the same problem and was surprised that my Iterable implementation could be very easily extended to an AbstractCollection implementation by simply adding the size() method (luckily I had the size of the collection :-)

    You should also consider to override Spliterator spliterator().

提交回复
热议问题