What is the difference between iterator and iterable and how to use them?
I am new in Java and I’m really confused with iterator and iterable. Can anyone explain to me and give some examples? 14 Answers 14
I am new in Java and I’m really confused with iterator and iterable. Can anyone explain to me and give some examples? 14 Answers 14
I am wondering why the Iterable interface does not provide the stream() and parallelStream() methods. Consider the following class: public class Hand implements Iterable<Card> { private final List<Card> list = new ArrayList<>(); private final int capacity; //… @Override public Iterator<Card> iterator() { return list.iterator(); } } It is an implementation of a Hand as you … Read more
In Java 8 we have the class Stream<T>, which curiously have a method Iterator<T> iterator() So you would expect it to implement interface Iterable<T>, which requires exactly this method, but that’s not the case. When I want to iterate over a Stream using a foreach loop, I have to do something like public static Iterable<T> … Read more
If I have a collection, such as Collection<String> strs, how can I get the first item out? I could just call an Iterator, take its first next(), then throw the Iterator away. Is there a less wasteful way to do it? 14 Answers 14
In my application I use 3rd party library (Spring Data for MongoDB to be exact). Methods of this library return Iterable<T>, while the rest of my code expects Collection<T>. Is there any utility method somewhere that will let me quickly convert one to the other? I would like to avoid creating a bunch of foreach … Read more
I have an interface which returns java.lang.Iterable<T>. I would like to manipulate that result using the Java 8 Stream API. However Iterable can’t “stream”. Any idea how to use the Iterable as a Stream without converting it to List? 8 s 8 There’s a much better answer than using spliteratorUnknownSize directly, which is both easier … Read more
What is the most basic definition of “iterable”, “iterator” and “iteration” in Python? I have read multiple definitions but I am unable to identify the exact meaning as it still won’t sink in. Can someone please help me with the 3 definitions in layman terms? 18 s 18 Iteration is a general term for taking … Read more
Is there a method like isiterable? The only solution I have found so far is to call hasattr(myObj, ‘__iter__’) But I am not sure how fool-proof this is. 2 22
An Iterable is a simple representation of a series of elements that can be iterated over. It does not have any iteration state such as a “current element”. Instead, it has one method that produces an Iterator. An Iterator is the object with iteration state. It lets you check if it has more elements using hasNext() and move to the next element … Read more