how to init an iterator - java

i just intent to initialize an iterator over a generic linked list like that (generic typ T seems to be erased in here since the site interpret it as tag)
public <T> LinkedList<T> sort(LinkedList<T> list){
Iterator<T> iter = new list.iterator();
...
but i got the error:
"list cannot be resolved"
what's wrong?

Remove the new keyword:
Iterator<T> iter = list.iterator();

To further clarify Mykola's correct answer: you're trying to create a new object of the class list. So you just want to call list.iterator() (which, somewhere inside it, is itself doing new Iterator or something like it and returning that to you).
Since you're clearly using Java 5 or above, though, the better way might be instead of doing
public <T> LinkedList<T> sort(LinkedList<T> list){
Iterator<T> iter = new list.iterator();
while (iter.hasNext()){
T t = iter.next();
...
}
}
instead doing this:
public <T> LinkedList<T> sort(LinkedList<T> list){
for (T t : list){
...
}
}
Still better, don't write that method at all and instead use
Collections.sort(list);

The word followed by new operator must be a Class name. Here list.iterator() is already returning a Object. So at this point new is uncessary.

Related

how to add an object to a set of some generic type in java with iterator?

I need to add elements from a LinkedList in a class to a Set. I tried to code the method; iterate , and then just add set.add(it.next()) but it did not work because the compiler said that it.next() is an Object, while my list contains elements of a generic type E, and so should my Set. Here is my approach :
Set<E> selectUniques() {
Set<E> set= new HashSet<>();
Iterator it = list.iterator();
while(it.hasNext()) {
if (frequency(it.next()) == 1) {
try {
E newob=(E) it.next();
set.add(newob);
}
catch( ClassCastException e) {
System.out.println("wrong list element type");
}
}
}
return set;
}
I know that since E extends Object, performing the cast that I did there is not alright. If there is a better solution even if it's without iterators? Note that I don't have the right to add parameters.
Iterator is also a generic class, so you can and should use Iterator<E> instead of a raw Iterator:
Iterator<E> it = list.iterator();
With that, next() will return an E instead of a plain old Object, and your compilation issue should be solved.
EDIT:
As Bohemian pointed out in the comments - make sure your list is a List<E> and not a raw List too.

How does one best explain what the iterable interface and iterator interface are? [duplicate]

I am new in Java and I'm really confused with iterator and iterable. Can anyone explain to me and give some examples?
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 (if any) using next().
Typically, an Iterable should be able to produce any number of valid Iterators.
An implementation of Iterable is one that provides an Iterator of itself:
public interface Iterable<T>
{
Iterator<T> iterator();
}
An iterator is a simple way of allowing some to loop through a collection of data without assignment privileges (though with ability to remove).
public interface Iterator<E>
{
boolean hasNext();
E next();
void remove();
}
See Javadoc.
I will answer the question especially about ArrayList as an example in order to help you understand better..
Iterable interface forces its subclasses to implement abstract method 'iterator()'.
public interface Iterable {
...
abstract Iterator<T> iterator(); //Returns an 'Iterator'(not iterator) over elements of type T.
...
}
Iterator interface forces its subclasses to implement abstract method 'hasNext()' and 'next()'.
public interface Iterator {
...
abstract boolean hasNext(); //Returns true if the iteration has more elements.
abstract E next(); //Returns the next element in the iteration.
...
}
ArrayList implements List, List extends Collection and Collection extends Iterable..
That is, you could see the relationship like
'Iterable <- Collection <- List <- ArrayList'
.
And Iterable, Collection and List just declare abstract method 'iterator()' and ArrayList alone implements it.
I am going to show ArrayList source code with 'iterator()' method as follows for more detailed information.
'iterator()' method returns an object of class 'Itr' which implements 'Iterator'.
public class ArrayList<E> ... implements List<E>, ...
{
...
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
...
public boolean hasNext() {
return cursor != size;
}
#SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
...
}
}
Some other methods or classes will iterate elements of collections like ArrayList through making use of Iterator (Itr).
Here is a simple example.
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
list.add("f");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String string = iterator.next();
System.out.println(string);
}
}
Now, is it clear? :)
I know this is an old question, but for anybody reading this who is stuck with the same question and who may be overwhelmed with all the terminology, here's a good, simple analogy to help you understand this distinction between iterables and iterators:
Think of a public library. Old school. With paper books. Yes, that kind of library.
A shelf full of books would be like an iterable. You can see the long line of books in the shelf. You may not know how many, but you can see that it is a long collection of books.
The librarian would be like the iterator. He can point to a specific book at any moment in time. He can insert/remove/modify/read the book at that location where he's pointing. He points, in sequence, to each book at a time every time you yell out "next!" to him. So, you normally would ask him: "has Next?", and he'll say "yes", to which you say "next!" and he'll point to the next book. He also knows when he's reached the end of the shelf, so that when you ask: "has Next?" he'll say "no".
I know it's a bit silly, but I hope this helps.
If a collection is iterable, then it can be iterated using an iterator (and consequently can be used in a for each loop.) The iterator is the actual object that will iterate through the collection.
The most important consideration is whether the item in question should be able to be traversed more than once. This is because you can always rewind an Iterable by calling iterator() again, but there is no way to rewind an Iterator.
Implementing Iterable interface allows an object to be the target of the "foreach" statement.
class SomeClass implements Iterable<String> {}
class Main
{
public void method()
{
SomeClass someClass = new SomeClass();
.....
for(String s : someClass) {
//do something
}
}
}
Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.
As explained here, The “Iterable” was introduced to be able to use in the foreach loop. A class implementing the Iterable interface can be iterated over.
Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.
Consider an example having 10 apples.
When it implements Iterable, it is like putting each apple in boxes from 1 to 10 and return an iterator which can be used to navigate.
By implementing iterator, we can get any apple, apple in next boxes etc.
So implementing iterable gives an iterator to navigate its elements although to navigate, iterator needs to be implemented.
Question:Difference between Iterable and Iterator?
Ans:
iterable: It is related to forEach loop
iterator: Is is related to Collection
The target element of the forEach loop shouble be iterable.
We can use Iterator to get the object one by one from the Collection
Iterable present in java.ḷang package
Iterator present in java.util package
Contains only one method iterator()
Contains three method hasNext(), next(), remove()
Introduced in 1.5 version
Introduced in 1.2 version
Basically speaking, both of them are very closely related to each other.
Consider Iterator to be an interface which helps us in traversing through a collection with the help of some undefined methods like hasNext(), next() and remove()
On the flip side, Iterable is another interface, which, if implemented by a class forces the class to be Iterable and is a target for For-Each construct.
It has only one method named iterator() which comes from Iterator interface itself.
When a collection is iterable, then it can be iterated using an iterator.
For understanding visit these:
ITERABLE: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Iterable.java
ITERATOR http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Iterator.java
Iterable were introduced to use in for each loop in java
public interface Collection<E> extends Iterable<E>
Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.
In addition to ColinD and Seeker answers.
In simple terms, Iterable and Iterator are both interfaces provided in Java's Collection Framework.
Iterable
A class has to implement the Iterable interface if it wants to have a for-each loop to iterate over its collection. However, the for-each loop can only be used to cycle through the collection in the forward direction and you won't be able to modify the elements in this collection. But, if all you want is to read the elements data, then it's very simple and thanks to Java lambda expression it's often one liner. For example:
iterableElements.forEach (x -> System.out.println(x) );
Iterator
This interface enables you to iterate over a collection, obtaining and removing its elements. Each of the collection classes provides a iterator() method that returns an iterator to the start of the collection. The advantage of this interface over iterable is that with this interface you can add, modify or remove elements in a collection. But, accessing elements needs a little more code than iterable. For example:
for (Iterator i = c.iterator(); i.hasNext(); ) {
Element e = i.next(); //Get the element
System.out.println(e); //access or modify the element
}
Sources:
Java Doc Iterable
Java Doc Iterator
An anonymous class easily converts an Iterator to an Iterable and lets you use the Iterable syntax (for loops, forEach()).
Example: consider an Iterator<T> it
for (T element : new Iterable<T>() {
#Override
public Iterator<T> iterator() {
return it;
}
}) {
//do something with `T element`
}
Abstracted in a function
static <T> Iterable<T> toIterable(Iterator<T> it) {
return new Iterable<T>() {
#Override
public Iterator<T> iterator() {
return it;
}
};
}
Usage
for (T element: toIterable(it) {
...
}
Most java interfaces ends with 'able'. examples are Iterable, Cloneable, Serializable, Runnable, etc. Therefore, Iterable is an interface that has an abstract method called iterator() which returns an Iterator object.
public interface Iterable {
abstract Iterator<T> iterator();
}
Iterator interface has abstract method 'hasNext()' and 'next()'.
public interface Iterator {
abstract boolean hasNext();
abstract E next();
}
A clear use is a List which extends->Collections Interface->extends Iterable
List<String> countrylist = new ArrayList<>();
list.add("US");
list.add("China");
list.add("Japan");
list.add("India");
Iterator<String> it = countrylist.iterator();
while (it.hasNext()) {
String string = it.next();
System.out.println(string);
}

Create List<T> instance from Iterator<T>

Anyone know if there is a standard way to create a List from an Iterator instance?
I tend towards Guava's Lists.newArrayList(Iterator) because I generally have Guava as a dependency, and it already exists.
Use the Iterator to get every element and add it to a List.
List<String> list = new LinkedList<String>();
while(iter.hasNext()) { // iter is of type Iterator<String>
list.add(iter.next());
}
I had this need, and as a user of Apache Commons, this is what I did:
IteratorUtils.toList(iterator);
Javadoc here: https://commons.apache.org/proper/commons-collections/javadocs/api-3.2.2/org/apache/commons/collections/IteratorUtils.html#toList(java.util.Iterator)
In Java 8 you can use these ways (while verbose enough):
Iterator<String> iterator = ...;
List<String> list = StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED), false)
.collect(Collectors.toList());
or
Iterator<String> iterator = ...;
List<String> list = new ArrayList<>(); // or LinkedList() if more relevant (adding being faster for LinkedList)
iterator.forEachRemaining(list::add);
try something like the following:
public T List<T> listFromIterator(Iterator<T> iterator) {
List<T> result = new LinkedList<T>();
while(iterator.hasNext()) {
result.add(iterator.next());
}
}
One thing to note is that if the iterator is not at the beginning of your structure, you have no way of retrieving previous elements.
If you have the collection that the iterator is from, you can create a list by using a constructor that takes a collection. ex: the LinkedList constructor:
LinkedList(Collection<? extends E> c)
This is the way that I convert from List to Iterator and vice versa.
ArrayList arrayList = new ArrayList();
// add elements to the array list
arrayList.add("C");
arrayList.add("A");
arrayList.add("E");
arrayList.add("B");
arrayList.add("D");
arrayList.add("F");
// use iterator to display contents of arrayList
System.out.print("Original contents of arrayList: ");
Iterator iterator = arrayList.iterator();
ArrayList arrayList2 = new ArrayList();
while(iterator.hasNext()) {
Object element = iterator.next();
arrayList2.add(element);
System.out.print(element + " ");
}

Java get last element of a collection

I have a collection, I want to get the last element of the collection. What's the most straighforward and fast way to do so?
One solution is to first toArray(), and then return the last element of the array. Is there any other better ones?
A Collection is not a necessarily ordered set of elements so there may not be a concept of the "last" element. If you want something that's ordered, you can use a SortedSet/NavigableSet which has a last() method. Or you can use a List and call mylist.get(mylist.size()-1);
If you really need the last element you should use a List or a SortedSet/NavigableSet. But if all you have is a Collection and you really, really, really need the last element, you could use toArray() or you could use an Iterator and iterate to the end of the list.
For example:
public Object getLastElement(final Collection c) {
final Iterator itr = c.iterator();
Object lastElement = itr.next();
while(itr.hasNext()) {
lastElement = itr.next();
}
return lastElement;
}
Iterables.getLast from Google Guava.
It has some optimization for Lists and SortedSets too.
It is not very efficient solution, but working one:
public static <T> T getFirstElement(final Iterable<T> elements) {
return elements.iterator().next();
}
public static <T> T getLastElement(final Iterable<T> elements) {
T lastElement = null;
for (T element : elements) {
lastElement = element;
}
return lastElement;
}
This should work without converting to List/Array:
collectionName.stream().reduce((prev, next) -> next).orElse(null)
Well one solution could be:
list.get(list.size()-1)
Edit: You have to convert the collection to a list before maybe like this: new ArrayList(coll)
A reasonable solution would be to use an iterator if you don't know anything about the underlying Collection, but do know that there is a "last" element. This isn't always the case, not all Collections are ordered.
Object lastElement = null;
for (Iterator collectionItr = c.iterator(); collectionItr.hasNext(); ) {
lastElement = collectionItr.next();
}
There isn't a last() or first() method in a Collection interface. For getting the last method, you can either do get(size() - 1) on a List or reverse the List and do get(0). I don't see a need to have last() method in any Collection API unless you are dealing with Stacks or Queues
Or you can use a for-each loop:
Collection<X> items = ...;
X last = null;
for (X x : items) last = x;
If you have Iterable convert to stream and find last element
Iterator<String> sourceIterator = Arrays.asList("one", "two", "three").iterator();
Iterable<String> iterable = () -> sourceIterator;
String last = StreamSupport.stream(iterable.spliterator(), false).reduce((first, second) -> second).orElse(null);

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?
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 (if any) using next().
Typically, an Iterable should be able to produce any number of valid Iterators.
An implementation of Iterable is one that provides an Iterator of itself:
public interface Iterable<T>
{
Iterator<T> iterator();
}
An iterator is a simple way of allowing some to loop through a collection of data without assignment privileges (though with ability to remove).
public interface Iterator<E>
{
boolean hasNext();
E next();
void remove();
}
See Javadoc.
I will answer the question especially about ArrayList as an example in order to help you understand better..
Iterable interface forces its subclasses to implement abstract method 'iterator()'.
public interface Iterable {
...
abstract Iterator<T> iterator(); //Returns an 'Iterator'(not iterator) over elements of type T.
...
}
Iterator interface forces its subclasses to implement abstract method 'hasNext()' and 'next()'.
public interface Iterator {
...
abstract boolean hasNext(); //Returns true if the iteration has more elements.
abstract E next(); //Returns the next element in the iteration.
...
}
ArrayList implements List, List extends Collection and Collection extends Iterable..
That is, you could see the relationship like
'Iterable <- Collection <- List <- ArrayList'
.
And Iterable, Collection and List just declare abstract method 'iterator()' and ArrayList alone implements it.
I am going to show ArrayList source code with 'iterator()' method as follows for more detailed information.
'iterator()' method returns an object of class 'Itr' which implements 'Iterator'.
public class ArrayList<E> ... implements List<E>, ...
{
...
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
...
public boolean hasNext() {
return cursor != size;
}
#SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
...
}
}
Some other methods or classes will iterate elements of collections like ArrayList through making use of Iterator (Itr).
Here is a simple example.
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("e");
list.add("f");
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String string = iterator.next();
System.out.println(string);
}
}
Now, is it clear? :)
I know this is an old question, but for anybody reading this who is stuck with the same question and who may be overwhelmed with all the terminology, here's a good, simple analogy to help you understand this distinction between iterables and iterators:
Think of a public library. Old school. With paper books. Yes, that kind of library.
A shelf full of books would be like an iterable. You can see the long line of books in the shelf. You may not know how many, but you can see that it is a long collection of books.
The librarian would be like the iterator. He can point to a specific book at any moment in time. He can insert/remove/modify/read the book at that location where he's pointing. He points, in sequence, to each book at a time every time you yell out "next!" to him. So, you normally would ask him: "has Next?", and he'll say "yes", to which you say "next!" and he'll point to the next book. He also knows when he's reached the end of the shelf, so that when you ask: "has Next?" he'll say "no".
I know it's a bit silly, but I hope this helps.
If a collection is iterable, then it can be iterated using an iterator (and consequently can be used in a for each loop.) The iterator is the actual object that will iterate through the collection.
The most important consideration is whether the item in question should be able to be traversed more than once. This is because you can always rewind an Iterable by calling iterator() again, but there is no way to rewind an Iterator.
Implementing Iterable interface allows an object to be the target of the "foreach" statement.
class SomeClass implements Iterable<String> {}
class Main
{
public void method()
{
SomeClass someClass = new SomeClass();
.....
for(String s : someClass) {
//do something
}
}
}
Iterator is an interface, which has implementation for iterate over elements. Iterable is an interface which provides Iterator.
As explained here, The “Iterable” was introduced to be able to use in the foreach loop. A class implementing the Iterable interface can be iterated over.
Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.
Consider an example having 10 apples.
When it implements Iterable, it is like putting each apple in boxes from 1 to 10 and return an iterator which can be used to navigate.
By implementing iterator, we can get any apple, apple in next boxes etc.
So implementing iterable gives an iterator to navigate its elements although to navigate, iterator needs to be implemented.
Question:Difference between Iterable and Iterator?
Ans:
iterable: It is related to forEach loop
iterator: Is is related to Collection
The target element of the forEach loop shouble be iterable.
We can use Iterator to get the object one by one from the Collection
Iterable present in java.ḷang package
Iterator present in java.util package
Contains only one method iterator()
Contains three method hasNext(), next(), remove()
Introduced in 1.5 version
Introduced in 1.2 version
Basically speaking, both of them are very closely related to each other.
Consider Iterator to be an interface which helps us in traversing through a collection with the help of some undefined methods like hasNext(), next() and remove()
On the flip side, Iterable is another interface, which, if implemented by a class forces the class to be Iterable and is a target for For-Each construct.
It has only one method named iterator() which comes from Iterator interface itself.
When a collection is iterable, then it can be iterated using an iterator.
For understanding visit these:
ITERABLE: http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/Iterable.java
ITERATOR http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/Iterator.java
Iterable were introduced to use in for each loop in java
public interface Collection<E> extends Iterable<E>
Iterator is class that manages iteration over an Iterable. It maintains a state of where we are in the current iteration, and knows what the next element is and how to get it.
In addition to ColinD and Seeker answers.
In simple terms, Iterable and Iterator are both interfaces provided in Java's Collection Framework.
Iterable
A class has to implement the Iterable interface if it wants to have a for-each loop to iterate over its collection. However, the for-each loop can only be used to cycle through the collection in the forward direction and you won't be able to modify the elements in this collection. But, if all you want is to read the elements data, then it's very simple and thanks to Java lambda expression it's often one liner. For example:
iterableElements.forEach (x -> System.out.println(x) );
Iterator
This interface enables you to iterate over a collection, obtaining and removing its elements. Each of the collection classes provides a iterator() method that returns an iterator to the start of the collection. The advantage of this interface over iterable is that with this interface you can add, modify or remove elements in a collection. But, accessing elements needs a little more code than iterable. For example:
for (Iterator i = c.iterator(); i.hasNext(); ) {
Element e = i.next(); //Get the element
System.out.println(e); //access or modify the element
}
Sources:
Java Doc Iterable
Java Doc Iterator
An anonymous class easily converts an Iterator to an Iterable and lets you use the Iterable syntax (for loops, forEach()).
Example: consider an Iterator<T> it
for (T element : new Iterable<T>() {
#Override
public Iterator<T> iterator() {
return it;
}
}) {
//do something with `T element`
}
Abstracted in a function
static <T> Iterable<T> toIterable(Iterator<T> it) {
return new Iterable<T>() {
#Override
public Iterator<T> iterator() {
return it;
}
};
}
Usage
for (T element: toIterable(it) {
...
}
Most java interfaces ends with 'able'. examples are Iterable, Cloneable, Serializable, Runnable, etc. Therefore, Iterable is an interface that has an abstract method called iterator() which returns an Iterator object.
public interface Iterable {
abstract Iterator<T> iterator();
}
Iterator interface has abstract method 'hasNext()' and 'next()'.
public interface Iterator {
abstract boolean hasNext();
abstract E next();
}
A clear use is a List which extends->Collections Interface->extends Iterable
List<String> countrylist = new ArrayList<>();
list.add("US");
list.add("China");
list.add("Japan");
list.add("India");
Iterator<String> it = countrylist.iterator();
while (it.hasNext()) {
String string = it.next();
System.out.println(string);
}

Categories