我有一个元组列表,我想找到具有最大值的元组x.在有多个最大值的情况下x,我想随机选择一个.我无法弄清楚如何实现这种随机选择功能.以下是我到目前为止的代码:
public void testSelectRandomFromLargestVals() {
List<Tuple<Integer, String>> list = new ArrayList<>();
list.add(new Tuple<>(5, "five-1"));
list.add(new Tuple<>(2, "two"));
list.add(new Tuple<>(3, "three"));
list.add(new Tuple<>(5, "five-2"));
list.add(new Tuple<>(5, "five-3"));
Optional<Tuple<Integer, String>> largestTuple = list.stream().max((t1, t2) -> Integer.compare(t1.x, t2.x));
System.out.println("Largest tuple is: " + largestTuple.get().x + " value is: " + largestTuple.get().y);
}
public class Tuple<X, Y> {
public final X x;
public final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
@Override …Run Code Online (Sandbox Code Playgroud) 有没有办法模拟Collections.shuffle的行为而没有比较器易受排序算法实现的影响,结果是安全的?
我的意思是不打破可比合同等.