简体   繁体   中英

How to find the minimum and maximum in a ArrayList<Entry> using Java

I'm trying to find the minimum and the maximum of a

ArrayList<Entry>

For example my ArrayList looks like this:

ArrayList<Entry> test = new ArrayList<Entry>();
test.add(new Entry(20, 0));
test.add(new Entry(5, 0));
test.add(new Entry(15, 0));

now I want the minimum(5) and the maximum(20) of this list.

I tried it with:

Collections.min(test);

But it says:

Bound mismatch: The generic method min(Collection<? extends T>) of type Collections is not applicable for the arguments (ArrayList<Entry>). The inferred type Entry is not a valid substitute for the bounded parameter <T extends Object & Comparable<? super T>>

I also tried:

test.length()

so I could do a for loop. But it also failed with this kind of ArrayList.

First, define a Comparator<Entry> which defines an ordering for Entry :

class EntryComparator implements Comparator<Entry> {
  @Override public int compare(Entry a, Entry b) {
    // ... whatever logic to compare entries.
    // Must return a negative number if a is "less than" b
    // Must return zero if a is "equal to" b
    // Must return a positive number if a is "greater than" b
  }
}

Then just iterate through the list, comparing each element to the current minimum and maximum elements:

Comparator<Entry> comparator = new EntryComparator();
Iterator<Entry> it = list.iterator();
Entry min, max;
// Assumes that the list is not empty
// (in which case min and max aren't defined anyway).

// Any element in the list is an upper bound on the min
// and a lower bound on the max.
min = max = it.next();

// Go through all of the other elements...
while (it.hasNext()) {
  Entry next = it.next();
  if (comparator.compare(next, min) < 0) {
    // Next is "less than" the current min, so take it as the new min.
    min = next;
  }
  if (comparator.compare(next, max) > 0) {
    // Next is "greater than" the current max, so take it as the new max.
    max = next;
  }
}

Entry has to implement the Comparator interface and provide an implementation for compare(T o1, T o2) .

compare returns 0 if o1 and o2 are equals, a positive value if o1 is less then o2, a negative value otherwise

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM