janlindso
janlindso

Reputation: 1233

Getting max from LinkedList

I'm making an application where the user can save travels with destination and length of travel. Then I somehow want to see what the longest are. All travels are objects in a LinkedList, and length of travel is integer.

How can I get the highest value of length of travel?

Solution: Ended up using iteration through nodes:

for (Travel travel : travelList) {
longest = travel.getLength();
destination = travel.getDest();
if (travel.getLength() >= longest)
{
    destination = travel.getDest();
}
}

Upvotes: 0

Views: 209

Answers (4)

Bhesh Gurung
Bhesh Gurung

Reputation: 51030

You can utilize the public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp).

You need to create a Comparator for you object first, and supply an instance of the comparator while calling the method.

Upvotes: 0

AC1
AC1

Reputation: 463

If you are storing travels using your own java object, then here's the pointer. Look at Collections.max () and Comparator and Comparable interfaces.

Upvotes: 0

ssantos
ssantos

Reputation: 16536

You may modify your Travel class so that it implements Comparable interface, and add something like.-

@Override
public int compareTo(Travel another) {
    return getLength().compareTo(another.getLength());
}

Then you can call

Collections.sort(travelsList);

to sort the list using your compare criteria defined in compareTo method

Upvotes: 0

Anton
Anton

Reputation: 6061

Consider iteration over each node of LinkedList to find out longest destination.

Upvotes: 1

Related Questions