【问题标题】:Compare two dependent fields in java Comparator比较java Comparator中的两个依赖字段
【发布时间】:2022-06-10 17:51:20
【问题描述】:

使用 java Comparator 我想获得具有更高值的最低索引。

  • 案例 1

| Index | Score |
| ----- | ------|
| 1     | 100   |
| 1     | 110   |
| 2     | 150   |

输出应该是 1 - 110

  • 案例 2
| Index | Score |
| ----- | ----- |
| 1     | null  |
| 1     | null  |
| 2     | 150   |
| 2     | 110   |

输出应该是 2 - 150

下面的代码给出了异常,而且我知道它不会提供预期的输出。

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CompareMe {
private int index;
private Integer score;

public CompareMe(int index, Integer score) {
    this.index = index;
    this.score = score;
}

public int getIndex() {
    return index;
}

public Integer getScore() {
    return score;
}

public static void main(String[] args) {

    List<CompareMe> list = new ArrayList<>();
    list.add(new CompareMe(1, 100));
    list.add(new CompareMe(1, 110));
    list.add(new CompareMe(2, 150));

    CompareMe max = Collections.max(list, Comparator.comparingInt(CompareMe::getIndex).reversed()
            .thenComparing(CompareMe::getScore));

    System.out.println(max.getIndex() + "-" + max.getScore());

    list = new ArrayList<>();
    list.add(new CompareMe(1, null));
    list.add(new CompareMe(1, null));
    list.add(new CompareMe(2, 150));
    list.add(new CompareMe(2, 110));

    max = Collections.max(list, Comparator.comparingInt(CompareMe::getIndex).reversed()
            .thenComparing(CompareMe::getScore));
    System.out.println(max.getIndex() + "-" + max.getScore());
}
}

【问题讨论】:

标签: java


猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-12
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多