[java] How can I get a first element from a sorted list?

I used Collections.sort(playersList); to sort a List. So, I think playersList is sorted now. But how can I get the first element of the list? playersList[0] does not work.

This question is related to java list sorting

The answer is


That depends on what type your list is, for ArrayList use:

list.get(0);

for LinkedList use:

list.getFirst();

if you like the array approach:

list.toArray()[0];

    public class Main {

    public static List<String> list = new ArrayList();

    public static void main(String[] args) {

        List<Integer> l = new ArrayList<>();

        l.add(222);
        l.add(100);
        l.add(45);
        l.add(415);
        l.add(311);

        l.sort(null);
        System.out.println(l.get(0));
    }
}

without l.sort(null) returned 222

with l.sort(null) returned 45


If you just want to get the minimum of a list, instead of sorting it and then getting the first element (O(N log N)), you can use do it in linear time using min:

<T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll)

That looks gnarly at first, but looking at your previous questions, you have a List<String>. In short: min works on it.

For the long answer: all that super and extends stuff in the generic type constraints is what Josh Bloch calls the PECS principle (usually presented next to a picture of Arnold -- I'M NOT KIDDING!)

Producer Extends, Consumer Super

It essentially makes generics more powerful, since the constraints are more flexible while still preserving type safety (see: what is the difference between ‘super’ and ‘extends’ in Java Generics)


You have to access lists a little differently than arrays in Java. See the javadocs for the List interface for more information.

playersList.get(0)

However if you want to find the smallest element in playersList, you shouldn't sort it and then get the first element. This runs very slowly compared to just searching once through the list to find the smallest element.

For example:

int smallestIndex = 0;
for (int i = 1; i < playersList.size(); i++) {
    if (playersList.get(i) < playersList.get(smallestIndex))
        smallestIndex = i;
}

playersList.get(smallestIndex);

The above code will find the smallest element in O(n) instead of O(n log n) time.


Matthew's answer is correct:

list.get(0);

To do what you tried:

list[0];

you'll have to wait until Java 7 is released:

devoxx conference http://img718.imageshack.us/img718/11/capturadepantalla201003cg.png

Here's an interesting presentation by Mark Reinhold about Java 7

It looks like parleys site is currently down, try later :(


If your collection is not a List (and thus you can't use get(int index)), then you can use the iterator:

Iterator iter = collection.iterator();
if (iter.hasNext()) {
    Object first = iter.next();
}

Using Java 8 streams, you can turn your list into a stream and get the first item in a list using the .findFirst() method.

List<String> stringsList = Arrays.asList("zordon", "alpha", "tommy");
Optional<String> optional = stringsList.stream().findFirst();
optional.get(); // "zordon"

The .findFirst() method will return an Optional that may or may not contain a string value (it may not contain a value if the stringsList is empty).

Then to unwrap the item from the Optional use the .get() method.


Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to list

Convert List to Pandas Dataframe Column Python find elements in one list that are not in the other Sorting a list with stream.sorted() in Java Python Loop: List Index Out of Range How to combine two lists in R How do I multiply each element in a list by a number? Save a list to a .txt file The most efficient way to remove first N elements in a list? TypeError: list indices must be integers or slices, not str Parse JSON String into List<string>

Examples related to sorting

Sort Array of object by object field in Angular 6 Sorting a list with stream.sorted() in Java How to sort dates from Oldest to Newest in Excel? how to sort pandas dataframe from one column Reverse a comparator in Java 8 Find the unique values in a column and then sort them pandas groupby sort within groups pandas groupby sort descending order Efficiently sorting a numpy array in descending order? Swift: Sort array of objects alphabetically