Perform operation on n random distinct elements from Collection using Streams API

前端 未结 7 1496
野趣味
野趣味 2020-12-03 17:30

I\'m attempting to retrieve n unique random elements for further processing from a Collection using the Streams API in Java 8, however, without much or any luck.

Mor

相关标签:
7条回答
  • 2020-12-03 18:32

    You could always create a "dumb" comparator, that will compare elements randomly in the list. Calling distinct() will ensure you that the elements are unique (from the queue).

    Something like this:

    static List<Integer> nDistinct(Collection<Integer> queue, int n) {
        final Random rand = new Random();
        return queue.stream()
                    .distinct()
                    .sorted(Comparator.comparingInt(a -> rand.nextInt()))
                    .limit(n)
                    .collect(Collectors.toList());
    }
    

    However I'm not sure it will be more efficient that putting the elements in the list, shuffling it and return a sublist.

    static List<Integer> nDistinct(Collection<Integer> queue, int n) {
        List<Integer> list = new ArrayList<>(queue);
        Collections.shuffle(list);
        return list.subList(0, n);
    }
    

    Oh, and it's probably semantically better to return a Set instead of a List since the elements are distincts. The methods are also designed to take Integers, but there's no difficulty to design them to be generic. :)

    Just as a note, the Stream API looks like a tool box that we could use for everything, however that's not always the case. As you see, the second method is more readable (IMO), probably more efficient and doesn't have much more code (even less!).

    0 讨论(0)
提交回复
热议问题