Java 8 查找Stream中重复的元素

作者 | 2020年4月12日

在本文中将向你展示如何找出Stream中重复的元素。

  • Set.add()
  • Collectors.groupingBy
  • Collections.frequency

在本文的最后,我们使用JMH对这些算法进行性能测试,找出运行速度最快的算法。

Stream.filter() 与 Set.add()

如果元素已经存在于集合中,则Set.add()方法会返回一个false,所有我们配合Stream.filter()方法可以找出Stream中的重复元素,在文章末尾我们会看到该算法的性能报告。

JavaDuplicated1.java

package com.mkyong;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class JavaDuplicated1 {

    public static void main(String[] args) {

        // 3, 4, 9
        List<Integer> list = Arrays.asList(5, 3, 4, 1, 3, 7, 2, 9, 9, 4);

        Set<Integer> result = findDuplicateBySetAdd(list);

        result.forEach(System.out::println);

    }

    public static <T> Set<T> findDuplicateBySetAdd(List<T> list) {

        Set<T> items = new HashSet<>();
        return list.stream()
                .filter(n -> !items.add(n)) // 如果元素已存在则Set.add()方法会返回false
                .collect(Collectors.toSet());

    }

}

输出

3
4
9

2. Map 与 Collectors.groupingBy

2.1 还可以借助Map与Collectors.groupingBy来统计出现次数大于1的元素。

JavaDuplicated2.java

package com.mkyong;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

public class JavaDuplicated2 {

    public static void main(String[] args) {

        // 3, 4, 9
        List<Integer> list = Arrays.asList(5, 3, 4, 1, 3, 7, 2, 9, 9, 4);

        Set<Integer> result = findDuplicateByGrouping(list);

        result.forEach(System.out::println);

    }

    public static <T> Set<T> findDuplicateByGrouping(List<T> list) {
        return list.stream()
                .collect(Collectors.groupingBy(Function.identity()
                        , Collectors.counting()))    // 创建一个 map {1=1, 2=1, 3=2, 4=2, 5=1, 7=1, 9=2}
                .entrySet().stream()                 // Map 转 Stream
                .filter(m -> m.getValue() > 1)       // 如果map中的统计的次数大于1说明是重复元素。
                .map(Map.Entry::getKey)
                .collect(Collectors.toSet());
    }

}

输出

3
4
9

3. Collections.frequency

Collections.frequency(list, i)方法返回元素i在list中的出现次数。

JavaDuplicated3.java

package com.mkyong;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class JavaDuplicated3 {

    public static void main(String[] args) {

        // 3, 4, 9
        List<Integer> list = Arrays.asList(5, 3, 4, 1, 3, 7, 2, 9, 9, 4);

        Set<Integer> result = findDuplicateByFrequency(list);

        result.forEach(System.out::println);

    }

    public static <T> Set<T> findDuplicateByFrequency(List<T> list) {

        return list.stream().filter(i -> Collections.frequency(list, i) > 1)
                .collect(Collectors.toSet());

    }

}

输出

3
4
9

4. JMH性能测试

下面我们使用JMH来对上面这些用于查找Stream中重复元素的算法进行性能测试。

pom.xml

  <dependency>
      <groupId>org.openjdk.jmh</groupId>
      <artifactId>jmh-core</artifactId>
      <version>1.23</version>
  </dependency>

  <dependency>
      <groupId>org.openjdk.jmh</groupId>
      <artifactId>jmh-generator-annprocess</artifactId>
      <version>1.23</version>
  </dependency>

BenchmarkFindDuplicate.java

package com.mkyong;

import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.infra.Blackhole;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
@Fork(value = 2, jvmArgs = {"-Xms4G", "-Xmx4G"})
public class BenchmarkFindDuplicate {

    private List<Integer> DATA_FOR_TESTING;

    @Setup
    public void init() {
        // random 1000 size
        DATA_FOR_TESTING = new Random().ints(1000, 1, 1000)
                .boxed()
                .collect(Collectors.toList());
    }

    public static void main(String[] args) throws RunnerException {

        Options opt = new OptionsBuilder()
                .include(BenchmarkFindDuplicate.class.getSimpleName())
                .forks(1)
                .build();

        new Runner(opt).run();

    }

    @Benchmark
    public void setAdd(Blackhole bh) {

        Set<Integer> items = new HashSet<>();
        Set<Integer> collect = DATA_FOR_TESTING.stream()
                .filter(n -> !items.add(n))
                .collect(Collectors.toSet());

        bh.consume(collect);

    }

    @Benchmark
    public void groupingBy(Blackhole bh) {

        Set<Integer> collect = DATA_FOR_TESTING.stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .entrySet()
                .stream()
                .filter(m -> m.getValue() > 1)
                .map(Map.Entry::getKey)
                .collect(Collectors.toSet());

        bh.consume(collect);

    }

    @Benchmark
    public void frequency(Blackhole bh) {

        Set<Integer> collect = DATA_FOR_TESTING.stream()
                .filter(i -> Collections.frequency(DATA_FOR_TESTING, i) > 1)
                .collect(Collectors.toSet());

        bh.consume(collect);

    }

}

输出

# JMH version: 1.23
# VM version: JDK 11.0.6, OpenJDK 64-Bit Server VM, 11.0.6+10
# VM invoker: /usr/lib/jvm/adoptopenjdk-11-hotspot-amd64/bin/java
# VM options: -Xms4G -Xmx4G
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: com.mkyong.BenchmarkFindDuplicate.frequency

# Run progress: 0.00% complete, ETA 00:05:00
# Fork: 1 of 1
# Warmup Iteration   1: 0.827 ms/op
# Warmup Iteration   2: 0.821 ms/op
# Warmup Iteration   3: 0.812 ms/op
# Warmup Iteration   4: 0.822 ms/op
# Warmup Iteration   5: 0.822 ms/op
Iteration   1: 0.814 ms/op
Iteration   2: 0.810 ms/op
Iteration   3: 0.779 ms/op
Iteration   4: 0.776 ms/op
Iteration   5: 0.814 ms/op

Result "com.mkyong.BenchmarkFindDuplicate.frequency":
  0.799 ±(99.9%) 0.075 ms/op [Average]
  (min, avg, max) = (0.776, 0.799, 0.814), stdev = 0.019
  CI (99.9%): [0.724, 0.874] (assumes normal distribution)

# JMH version: 1.23
# VM version: JDK 11.0.6, OpenJDK 64-Bit Server VM, 11.0.6+10
# VM invoker: /usr/lib/jvm/adoptopenjdk-11-hotspot-amd64/bin/java
# VM options: -Xms4G -Xmx4G
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: com.mkyong.BenchmarkFindDuplicate.groupingBy

# Run progress: 33.33% complete, ETA 00:03:20
# Fork: 1 of 1
# Warmup Iteration   1: 0.040 ms/op
# Warmup Iteration   2: 0.038 ms/op
# Warmup Iteration   3: 0.037 ms/op
# Warmup Iteration   4: 0.036 ms/op
# Warmup Iteration   5: 0.039 ms/op
Iteration   1: 0.039 ms/op
Iteration   2: 0.039 ms/op
Iteration   3: 0.039 ms/op
Iteration   4: 0.039 ms/op
Iteration   5: 0.039 ms/op

Result "com.mkyong.BenchmarkFindDuplicate.groupingBy":
  0.039 ±(99.9%) 0.001 ms/op [Average]
  (min, avg, max) = (0.039, 0.039, 0.039), stdev = 0.001
  CI (99.9%): [0.038, 0.040] (assumes normal distribution)

# JMH version: 1.23
# VM version: JDK 11.0.6, OpenJDK 64-Bit Server VM, 11.0.6+10
# VM invoker: /usr/lib/jvm/adoptopenjdk-11-hotspot-amd64/bin/java
# VM options: -Xms4G -Xmx4G
# Warmup: 5 iterations, 10 s each
# Measurement: 5 iterations, 10 s each
# Timeout: 10 min per iteration
# Threads: 1 thread, will synchronize iterations
# Benchmark mode: Average time, time/op
# Benchmark: com.mkyong.BenchmarkFindDuplicate.setAdd

# Run progress: 66.67% complete, ETA 00:01:40
# Fork: 1 of 1
# Warmup Iteration   1: 0.027 ms/op
# Warmup Iteration   2: 0.028 ms/op
# Warmup Iteration   3: 0.026 ms/op
# Warmup Iteration   4: 0.026 ms/op
# Warmup Iteration   5: 0.027 ms/op
Iteration   1: 0.026 ms/op
Iteration   2: 0.027 ms/op
Iteration   3: 0.028 ms/op
Iteration   4: 0.028 ms/op
Iteration   5: 0.028 ms/op

Result "com.mkyong.BenchmarkFindDuplicate.setAdd":
  0.027 ±(99.9%) 0.003 ms/op [Average]
  (min, avg, max) = (0.026, 0.027, 0.028), stdev = 0.001
  CI (99.9%): [0.024, 0.031] (assumes normal distribution)

# Run complete. Total time: 00:05:01

REMEMBER: The numbers below are just data. To gain reusable insights, you need to follow up on
why the numbers are the way they are. Use profilers (see -prof, -lprof), design factorial
experiments, perform baseline and negative tests that provide experimental control, make sure
the benchmarking environment is safe on JVM/OS/HW level, ask for reviews from the domain experts.
Do not assume the numbers tell you what you want them to tell.

Benchmark                          Mode  Cnt  Score   Error  Units
BenchmarkFindDuplicate.frequency   avgt    5  0.799 ± 0.075  ms/op
BenchmarkFindDuplicate.groupingBy  avgt    5  0.039 ± 0.001  ms/op
BenchmarkFindDuplicate.setAdd      avgt    5  0.027 ± 0.003  ms/op

Process finished with exit code 0

由结果可见,在Java 8 Stream中,使用Stream.filter() + Set.add()的组合才是查找重复元素最快的算法,因为它只需要执行一次循环。

使用Collections.frequency则是最慢的算法,因为它会统计每个元素在集合list中的出现的所有次数,随着list规模的增长,该算法会越来越慢。

return list.stream().filter(i -> Collections.frequency(list, i) > 1)
        .collect(Collectors.toSet());

发表评论

电子邮件地址不会被公开。 必填项已用*标注