I have this commands:
list.stream()
.filter(e -> ...)
.sorted(comparatorShuffle())
.findAny()
.orElse(null);
This is comparatorShuffle()
:
public static <E> Comparator<E> comparatorShuffle(){
return new Comparator<>(){
private final List<Integer> temp = List.of(-1, 1);
private final Random random = new Random();
@Override
@SuppressWarnings("ComparatorMethodParameterNotUsed")
public int compare(E o1, E o2){
return temp.get(random.nextInt(temp.size()));
}
};
}
Sometimes I get an exception: IllegalArgumentException: Comparison method violates its general contract!
I understand why I get this, it's because the sort(it's random) don't respect the rule: if A > B && B > C then A > C
There is a way to suppress/ignore this error? Or another way to shuffle the stream without using collect
?