java - 如何使用 Java 查找 ArrayList<Entry> 中的最小值和最大值

标签 java android arraylist

我正在尝试找到最小值和最大值

ArrayList<Entry>

例如我的 ArrayList 看起来像这样:

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

现在我想要这个列表的最小值(5)和最大值(20)。

我尝试过:

Collections.min(test);

但它说:

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>>

我也尝试过:

test.length()

所以我可以做一个for循环。但对于这种 ArrayList 也失败了。

最佳答案

首先,定义一个Comparator<Entry>它定义了 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
  }
}

然后遍历列表,将每个元素与当前的最小和最大元素进行比较:

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;
  }
}

关于java - 如何使用 Java 查找 ArrayList<Entry> 中的最小值和最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33914991/

相关文章:

java.lang.NoClassDefFoundError : javax/persistence/EntityListeners 错误

java - 寻找设计模式和列表来存储多种类型(对象和整数)

android - 如何从 Uri 调整图像大小?

java - 在 ActionBarSherlock 的 NavigationTab 示例中使用 fragment

java - 使用可比较的类保留 2D Arraylist 的原始索引

java - 带有 android 支持库 v7 的 maven android 插件

java - Spring/JPA/JSF 的异常处理策略

java - 如何检查 firebase 实时数据库中是否存在特定值?

java - 将txt文件的不同行读取到不同的ArrayList中

java - 如何从字符串数组或数组列表创建一个字符串?