Shuffle/Random comparator

后端 未结 3 727
别跟我提以往
别跟我提以往 2020-12-20 02:54

IS there any way to emulate the behavior of Collections.shuffle without a comparator being vulnerable to the sorting algorithm implementation for the result to be safe?

3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-20 03:55

    A bit more generic to the previous answer, when the type of element is not known:

    public static  Comparator shuffle() {
        final Map uniqueIds = new IdentityHashMap<>();
        return Comparator.comparing(e -> uniqueIds.computeIfAbsent(e, k -> UUID.randomUUID()));
    }
    

    can be used in streams as well:

    list.stream().sorted(Streams.shuffle()).collect(Collectors.toList())
    

    there might be collisions somehow, so it can be extended using a HashSet for the UUID to check this case

提交回复
热议问题