I have a list of tuples, and I want to find the tuples with the largest x
value. In the case where there are multiple largest x
values, I want to choose one at random. I can't figure out how to implement this random selection functionality. Below is the code I have so far:
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
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Tuple<?, ?> tuple = (Tuple<?, ?>) o;
if (!x.equals(tuple.x)) return false;
return y.equals(tuple.y);
}
@Override
public int hashCode() {
int result = x.hashCode();
result = 31 * result + y.hashCode();
return result;
}
}