0

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();
}
}
Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
janlindso
  • 1,225
  • 3
  • 16
  • 41
  • 2
    Have you tried anything yourself? – sanbhat Apr 08 '13 at 16:52
  • I have tried Collections.max(MyTravelList), but without any luck. Got an error. I guess that it sort list in total, and not only by length. – janlindso Apr 08 '13 at 16:54
  • http://docs.oracle.com/javase/6/docs/api/java/util/Collections.html#max(java.util.Collection) , also check Comparable, these are the tools you need... try yourself you should be able to get it. Also this previous post will be useful http://stackoverflow.com/questions/369383/best-way-for-get-min-and-max-value-from-a-list-of-comparables-in-java – AurA Apr 08 '13 at 16:57

4 Answers4

1

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

Anton
  • 5,831
  • 3
  • 35
  • 45
  • Actually, this will be working. Saving node in variable if highest. It seems this is easier to do than using a Comparator. But which is best, and why? – janlindso Apr 08 '13 at 17:02
  • There is no much difference, take a look at source code of Collection.max method. It does the same things and it requires N iteration. Probably, you can find max method more elegant. – Anton Apr 08 '13 at 17:11
0

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

AC1
  • 463
  • 3
  • 9
0

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.

Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
0

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

ssantos
  • 16,001
  • 7
  • 50
  • 70