Detect duplicated groups in stream

后端 未结 3 1751
没有蜡笔的小新
没有蜡笔的小新 2021-02-20 10:32

I want to ensure that all numbers in the list are grouped together. Let me explain this on examples:

{1, 1, 1, 2, 2}    // OK, two distinct groups
{1, 1, 2, 2, 1         


        
3条回答
  •  走了就别回头了
    2021-02-20 11:23

    In my opinion this problem doesn't fit the Stream API at all but I was curious how this could be implemenented (however in a performant way).

    The problem is that you have to keep track of seen elements and the whole test should have a short-circuit behaviour. So I came up with this solution (without Streams):

    public static boolean hasUniqueGroups(int[] arr) {
        Objects.requireNonNull(arr);
        Set seen = new HashSet<>();
        for (int i = 0; i < arr.length; i++) {
            if (i == 0 || arr[i] != arr[i - 1]) {
                if (!seen.add(arr[i])) {
                    return false;
                }
            }
        }
        return true;
    }
    

    The next step is to introduce the Stream API and the solution looks like this:

    public static boolean hasUniqueGroups(int[] arr) {
        Objects.requireNonNull(arr);
        Set seen = new HashSet<>();
        return IntStream.range(0, arr.length)
                .filter(i -> i == 0 || arr[i] != arr[i - 1])
                .mapToObj(i -> arr[i])
                .allMatch(seen::add);
    }
    

    Note: In order to parallelize this Stream you should use a thread-safe Set.

提交回复
热议问题