我假设您将性能作为最有效方式的关键。在这种情况下,简单的基准测试可以提供最佳答案。这是一个简单的 JMH 基准测试:
package test;
import org.openjdk.jmh.annotations.*;
import java.util.*;
import java.util.stream.Collectors;
public class ListOfStringsToSetBenchmark {
public static void main(String[] args) throws Exception {
org.openjdk.jmh.Main.main(args);
}
@Benchmark
@Fork(value = 1, warmups = 1)
@Measurement(iterations = 5)
@Warmup(iterations = 3)
@BenchmarkMode(Mode.Throughput)
public void streams() {
Map<String, List<String>> map = new HashMap<>();
map.put("test", Arrays.asList("1", "2", "3"));
map.put("test2", Arrays.asList("4", "5", "6"));
map.put("test3", Arrays.asList("7", "8", "9"));
Set<String> collect = map.values().stream().flatMap(Collection::stream).collect(Collectors.toSet());
}
@Benchmark
@Fork(value = 1, warmups = 1)
@Measurement(iterations = 5)
@Warmup(iterations = 3)
@BenchmarkMode(Mode.Throughput)
public void parallelStreams() {
Map<String, List<String>> map = new HashMap<>();
map.put("test", Arrays.asList("1", "2", "3"));
map.put("test2", Arrays.asList("4", "5", "6"));
map.put("test3", Arrays.asList("7", "8", "9"));
Set<String> collect = map.values().parallelStream().flatMap(Collection::parallelStream).collect(Collectors.toSet());
}
@Benchmark
@Fork(value = 1, warmups = 1)
@Measurement(iterations = 5)
@Warmup(iterations = 3)
@BenchmarkMode(Mode.Throughput)
public void forEach() {
Map<String, List<String>> map = new HashMap<>();
map.put("test", Arrays.asList("1", "2", "3"));
map.put("test2", Arrays.asList("4", "5", "6"));
map.put("test3", Arrays.asList("7", "8", "9"));
Set<String> set = new HashSet<>();
for (List<String> localList : map.values()) {
set.addAll(localList);
}
}
}
结果
Benchmark Mode Cnt Score Error Units
ListOfStringsToSetBenchmark.forEach thrpt 5 5290023,805 ± 89846,320 ops/s
ListOfStringsToSetBenchmark.parallelStreams thrpt 5 588714,960 ± 6289,819 ops/s
ListOfStringsToSetBenchmark.streams thrpt 5 2940686,522 ± 359335,288 ops/s
注意:为了获得精确的结果,您需要增加迭代值。