ArrayList Find First and Last Element

I would suggest you to use Google Guava for that. The getLast method will throw NoSuchElementException if the list is empty:

lastElement = Iterables.getLast(iterableList);

And to get the first element:

firstElement = Iterables.getFirst(iterable, defaultValue)

For more information about Java Collections, check it out.


Its always advised to use Iterators or ListIterator to iterate through a list. Using the list size as reference does not workout when you are modifying the list data (removing or inserting elements).

Iterator - allow the caller to iterate through a list in one direction and remove elements from the underlying collection during the iteration with well-defined semantics

You can use a ListIterator to iterate through the list. A ListIterator allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the iterator's current position in the list. You can refer the below example.

ArrayList<String> list = new ArrayList<String>();
    ListIterator<String> iterator = list.listIterator();
    while(iterator.hasNext()){
        System.out.println(iterator.next());
        ...
        ...
        System.out.println(iterator.previous());
        if(!iterator.hasPrevious()){
            System.out.println("at start of the list");
        }else if(!iterator.hasNext()){
            System.out.println("at end of the list");
        }

    }

This is just an example showing the usage of a ListIterator, please analyze what your requirement is and implement as required.


List<YourData> list = new ArrayList<YourData>();

for(int index=0; index < list.size(); index++) {

    YourData currElement = list.get(index);

    if(index == 0) {
        //currElement is the first element
    }

    if(index == list.size() - 1) {
         //currElement is the last element
    }
}

Tags:

Java

Android