Java get last element of a collection - java

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);

Related

Removing elements from array in java throws exception [duplicate]

This question already has answers here:
Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop
(31 answers)
Closed 8 years ago.
I'm trying to remove some elements from an ArrayList while iterating it like this:
for (String str : myArrayList) {
if (someCondition) {
myArrayList.remove(str);
}
}
Of course, I get a ConcurrentModificationException when trying to remove items from the list at the same time when iterating myArrayList. Is there some simple solution to solve this problem?
Use an Iterator and call remove():
Iterator<String> iter = myArrayList.iterator();
while (iter.hasNext()) {
String str = iter.next();
if (someCondition)
iter.remove();
}
As an alternative to everyone else's answers I've always done something like this:
List<String> toRemove = new ArrayList<String>();
for (String str : myArrayList) {
if (someCondition) {
toRemove.add(str);
}
}
myArrayList.removeAll(toRemove);
This will avoid you having to deal with the iterator directly, but requires another list. I've always preferred this route for whatever reason.
Java 8 user can do that: list.removeIf(...)
List<String> list = new ArrayList<>(Arrays.asList("a", "b", "c"));
list.removeIf(e -> (someCondition));
It will remove elements in the list, for which someCondition is satisfied
You have to use the iterator's remove() method, which means no enhanced for loop:
for (final Iterator iterator = myArrayList.iterator(); iterator.hasNext(); ) {
iterator.next();
if (someCondition) {
iterator.remove();
}
}
No, no, NO!
In single threated tasks you don't need to use Iterator, moreover, CopyOnWriteArrayList (due to performance hit).
Solution is much simpler: try to use canonical for loop instead of for-each loop.
According to Java copyright owners (some years ago Sun, now Oracle) for-each loop guide, it uses iterator to walk through collection and just hides it to make code looks better. But, unfortunately as we can see, it produced more problems than profits, otherwise this topic would not arise.
For example, this code will lead to java.util.ConcurrentModificationException when entering next iteration on modified ArrayList:
// process collection
for (SomeClass currElement: testList) {
SomeClass founDuplicate = findDuplicates(currElement);
if (founDuplicate != null) {
uniqueTestList.add(founDuplicate);
testList.remove(testList.indexOf(currElement));
}
}
But following code works just fine:
// process collection
for (int i = 0; i < testList.size(); i++) {
SomeClass currElement = testList.get(i);
SomeClass founDuplicate = findDuplicates(currElement);
if (founDuplicate != null) {
uniqueTestList.add(founDuplicate);
testList.remove(testList.indexOf(currElement));
i--; //to avoid skipping of shifted element
}
}
So, try to use indexing approach for iterating over collections and avoid for-each loop, as they are not equivalent!
For-each loop uses some internal iterators, which check collection modification and throw ConcurrentModificationException exception. To confirm this, take a closer look at the printed stack trace when using first example that I've posted:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)
at TestFail.main(TestFail.java:43)
For multithreading use corresponding multitask approaches (like synchronized keyword).
While other suggested solutions work, If you really want the solution to be made thread safe you should replace ArrayList with CopyOnWriteArrayList
//List<String> s = new ArrayList<>(); //Will throw exception
List<String> s = new CopyOnWriteArrayList<>();
s.add("B");
Iterator<String> it = s.iterator();
s.add("A");
//Below removes only "B" from List
while (it.hasNext()) {
s.remove(it.next());
}
System.out.println(s);
If you want to modify your List during traversal, then you need to use the Iterator. And then you can use iterator.remove() to remove the elements during traversal.
List myArrayList = Collections.synchronizedList(new ArrayList());
//add your elements
myArrayList.add();
myArrayList.add();
myArrayList.add();
synchronized(myArrayList) {
Iterator i = myArrayList.iterator();
while (i.hasNext()){
Object object = i.next();
}
}
One alternative method is convert your List to array, iterate them and remove them directly from the List based on your logic.
List<String> myList = new ArrayList<String>(); // You can use either list or set
myList.add("abc");
myList.add("abcd");
myList.add("abcde");
myList.add("abcdef");
myList.add("abcdefg");
Object[] obj = myList.toArray();
for(Object o:obj) {
if(condition)
myList.remove(o.toString());
}
You can use the iterator remove() function to remove the object from underlying collection object. But in this case you can remove the same object and not any other object from the list.
from here

Can I subclass "standard" arraylist iterator?

I need to iterate all the elements of ArrayList except the last one. So I want to create such iterator. But I don't what to implement the whole iterator, I need to override only the hasNext() method, so I would like to subclass a "standard" iterator. Is there any way to do that?
I think the better way to do that rather than overriding the default iterator is to iterate the ArrayList on your own. An ArrayListhas a couple of method defined that can help you accomplish the task: get(int) and size().
Everything you have to do is to get the total number of elements in the ArrayList(with size()) and then loop through the elements accessing each element directly in each iteration using the get() method. Your code would look something like this:
for(int i = 0; i < myList.size() - 1; i++){
element = myList.get(i);
//do something
}
Now with this principle in mind, you may create your own class to iterate the ArrayList.
It would be odd to modify the iterator to perform this traversal. The obvious thing to do is to write the "algorithm" as you want it:
public static <T> void eachExceptLast(List<? extends T> list, Operation<T> op) {
Iterator<T> iter = list.iterator();
if (!iter.hasNext()) {
return;
}
T item = iter.next();
while (iter.hasNext()) {
op.run(item);
item = iter.next();
}
}
(Or use an index assuming a RandomAccess list.)
However, there's a much better way of doing this. list.subList(0, list.size()-1) (for a non-empty list) will return a view of the original list less the last element. It doesn't do a copy, and you can even use Iterator.remove.
You can create a class that implements either the Iterator or ListIterator interfaces and then override the hasNext() method .

Should we avoid hasNext() call in an Iterator?

Is it advisable not to use iterator.hasNext() in looping over an iterator?
For example I would like to set value obj to each element of a list. I could use the following code or make it more readable by using hasNext() in a loop.
int size = list.size();
ListIterator<? super T> itr = list.listIterator();
for (int i=0; i<size; i++) {
itr.next();
itr.set(obj);
}
Instead of these lines I could write my code like the following.
for (ListIterator<? super T> itr = list.listIterator(); itr.hasNext(); ) {
itr.next();
itr.set(obj);
}
Is it advisable not to use iterator.hasNext() in looping over an iterator?
Um, no. hasNext is the standard way you iterate with an iterator. That's what the enhanced-for statement does behind the scenes for an iterable, for example.
Having said that, your code is already ListIterator-specific, as you're using ListIterator.set - so your second block of code won't actually compile at the moment. Even if it did, it wouldn't work, as you still need to call next(). This would work though:
for (ListIterator<? super T> itr = list.listIterator(); itr.hasNext(); ) {
itr.next();
itr.set(obj);
}
Well, when NetBeans refactor you for-each loop to use of iterators, they do it in following way.
for-each:
for (T object : list) {
}
iterator pattern:
for (Iterator<T> it = list.iterator(); it.hasNext();) {
T object = it.next();
}
I think it is totally okay to use hasNext() on iterator while iterating.
There is no such recommendation not to use hasNext.
The Iterator API list has just three methods, add, remove and hasNext
Also from clean code the second approach looks far better then the first one.
When using an iterator, you should always call the hasNext() method. Otherwise, you may run into a NoSuchElementException when calling the next() method.
Of course, you should use hasNext(), but only for iterating over a collection, not for populating the collection. To fill the collection, work on the collection itself, not on it's iterator and to read from the collection use the for loop as described by #JMelnik.
Fill the collection
Collection<MyObject> list = ...;
while (something) {
list.add(myObject);
}
Read the collection
for (MyObject myObject : list) {
...
}

Why does calling remove() on an iterator give a ConcurrentModificationException?

I am trying to write a very simple method to remove duplicates in a LinkedList:
I try to do this without using additional buffer, so I maintain two iterators on the linked list, one does the normal iteration, and another iterates through all prior nodes to check for dupes (as indicated in CareerCup); however, the compiler tells me there is a CME even though I am calling itr1.remove():
public static void RemoveWithoutBuffer(LinkedList l) {
ListIterator itr1 = l.listIterator();
int count1 = 0;
int count2 = 0;
while (itr1.hasNext()) {
Object next = itr1.next();
count1++;
count2 = 0;
ListIterator itr2 = l.listIterator();
while (itr2.hasNext()) {
count2++;
if (count2 == count1)
break;
if (itr2.next() == next){
itr1.remove();
}
}
}
}
Another simpler solution of this problem with the aid of hashset is easy as follows, and no exception reported:
public static void Remove(LinkedList l) {
HashSet set = new HashSet();
ListIterator itr = l.listIterator();
while (itr.hasNext()) {
Object next = itr.next();
if (set.contains(next))
itr.remove();
else
set.add(next);
}
}
Is it because when I am iterating through itr2 I cannot modify on itr1? Is there a way to fix this? Thank you guys.
In the first case yes - you're altering the collection's contents via iterator2, while iterator1 is not aware about the changes. In the second case HashSet/HashMap don't allow removing elements while iterating through them.
You can add removed elements to another collection, and removeAll them after an iteration. E.g.
List toRemove = new ArrayList();
for (Object next : collection) {
if (someCondition) toRemove.add(next);
}
collection.removeAll(toRemove);
I hope it helps.
P.S. more details on how to remove elements from list, concerning algorithm complexity you can read here Removing ArrayList object issue
From the API docs:
The iterators returned by this class's iterator and listIterator
methods are fail-fast: if the list is structurally modified at any
time after the iterator is created, in any way except through the
Iterator's own remove or add methods, the iterator will throw a
ConcurrentModificationException.
You are getting CME because the list is modified by second iterator and first iterator is not aware of that change. When next time it tries to access the list, it is already modified. And hence it throws the exception.
Please use only one iterator to modify list at a time.
Yes. You can think of it this way: when you create an iterator it gets the list's current "modification count". When an iterator removes an element from the list, it checks the modification count to see if it is what it expects, and if all is okay, it removes the element and updates the modification count on both the iterator and the list. The other iterator will still have the old modification count and see the new value and throw the CME.
The hashset based way is the right solution in most cases. It will perform much better--two O(n) passes is usually better than O(n^2) as the nested iteration solution would produce (if it worked).
The reason why you get CME was explained by others, here is possible way you can use to remove dups
Use a List toRemove to record element at the first time iterator stumble into it, afterwards when meet again with the recorded element, remove it using iterator.remove()
private void removeDups(List list) {
List toRemove = new ArrayList();
for(Iterator it = list.iterator(); it.hasNext();) {
Object next = it.next();
if(!toRemove.contains(next)) {
toRemove.add(next);
} else {
it.remove();
}
}
toremove.clear();
}
Yes, you can fix this without using extra space.
The problem comes from executing these two lines, one after another.
itr1.remove();
itr2.hasNext();
You can use two iterators over the same list at the same time. If you are careful.
But once one of those iterators has modified the list (as it happens with itr1.remove() ) you can no longer use the other iterator (so you can't call itr2.hasNext()).
The solution is to put a break after itr1.remove(). And to update count1 :
public static void RemoveWithoutBuffer(LinkedList l) {
ListIterator itr1 = l.listIterator();
int count1 = 0;
int count2 = 0;
while (itr1.hasNext()) {
Object next = itr1.next();
count1++;
count2 = 0;
ListIterator itr2 = l.listIterator();
while (itr2.hasNext()) {
count2++;
if (count2 == count1)
break;
if (itr2.next() == next){
itr1.remove();
--count1;
break;
}
}
}
}
A more elegant solution would be to compare with elements after the current one rather than elements before the current one :
public static void RemoveWithoutBuffer(LinkedList l) {
ListIterator itr1 = l.listIterator();
while (itr1.hasNext()) {
Object next = itr1.next();
ListIterator itr2 = l.listIterator( itr1.nextIndex() );
while (itr2.hasNext()) {
if (itr2.next() == next) {
itr1.remove();
break;
}
}
}
}
These are not the best solutions in terms of computational complexity. If memory space is not an issue the hashset solution is a better one regarding computational complexity.
But the question is about concurrent mofication through iterators and not about complexity optimization.

Iterator has .next() - is there a way to get the previous element instead of the next one?

I have an Iterator that I use on a HashMap, and I save and load the iterator.
is there a way to get the previous key in the HashMap with Iterator? (java.util.Iterator)
Update
I save it as an attribute in a Red5 connection and then load it back to continue working where i stopped.
Another update
I'm iterating through the keyset of the HashMap
You can use ListIterator instead of Iterator.
ListIterator has previous() and hasPrevious() methods.
Not directly, as others pointed out, but if you e.g. need to access one previous element you could easily save that in a separate variable.
T previous = null;
for (Iterator<T> i = map.keySet().iterator(); i.hasNext();) {
T element = i.next();
// Do something with "element" and "previous" (if not null)
previous = element;
}
It sounds like you want the array semantics more akin to a ListIterator rather than those provided by the Iterator interface. The easiest way to acquire such a thing is likely to construct a list ( from the key-set (LinkedList<K> keyList = new LinkedList<K>(map.keySet())), then use a ListIterator manually instead of a regular Iterator or foreach.
For very simple cases of needing to remember consecutive items, the simplest way to handle this is to store the previous Key in a local variable and update it at the end of the loop.
No, an Iterator<E> defines only 3 methods:
boolean hasNext()
E next()
void remove()
You can of course implement your own iterator.
As others have said, you only access an element using next(). However it's sort of a matter of terminology. Once you call next() this is the current element.
Unless the problem is you need to see two consecutive items in the collection each iteration, in which case a simple variable would seem easiest.
Although Set doesn't provide a method for a reverse iterator, Deque does. You can use descendingIterator() for an iterator in reverse order and iterator(), for an iterator in forwards order.
(You can create a Deque from a Set via Deque<T> deque = new LinkedList<T>(set), where set is your Set and T the generic type you're using.)
Ultimately Iterators are not fully suited for your task.
Why not create a List from your Set (via, eg, List list = new LinkedList(set)) and iterate by using a standard indexed for-loop? That way you know the previous element is at i - 1.
using iterator, No you dont have an option to get a previous key value. it has only hasNext() and next() methods.
No, you can't. The Iterator interface has no method to get the previous element.
But what you can do is - a little bit rubbish- creating a List<Entry<Integer, YourObjectType>> where the Integer-value represents the hash-code of the key-object. Then you can do something like this:
for (int i = 0; i < list.size(); i++)
{
YourObjectType current = list.get(i).getValue();
YourObjectType previous = (i == 0 ? null : list.get(i - 1).getValue());
// Do whatever you want
}
I know this is very rubbish, but it is possible
Make your own Iterator:
public class EnhancedIterator<E> implements Iterator<E>{
private List<E> list;
private int indexSelected=-1;
public EnhancedIterator(List<E> list){
this.list=list;
}
#Override
public boolean hasNext() {
return indexSelected<list.size()-1;
}
#Override
public E next() {
indexSelected++;
return current();
}
#Override
public void remove() {
list.remove(indexSelected);
}
public void remove(int i){
list.remove(i);
if(i<indexSelected){
indexSelected--;
}
}
public E previous(){
indexSelected--;
return current();
}
public E current(){
return list.get(indexSelected);
}
public E get(int i){
return list.get(i);
}
}

Categories