请参阅下面的简单示例,该示例计算列表中每个单词的出现次数:
Stream<String> words = Stream.of("a", "b", "a", "c");
Map<String, Integer> wordsCount = words.collect(toMap(s -> s, s -> 1,
(i, j) -> i + j));
Run Code Online (Sandbox Code Playgroud)
最后,wordsCount是{a=2, b=1, c=1}.
但我的流非常大,我想要并行工作,所以我写道:
Map<String, Integer> wordsCount = words.parallel()
.collect(toMap(s -> s, s -> 1,
(i, j) -> i + j));
Run Code Online (Sandbox Code Playgroud)
但是我注意到这wordsCount很简单HashMap所以我想知道我是否需要明确要求并发映射以确保线程安全:
Map<String, Integer> wordsCount = words.parallel()
.collect(toConcurrentMap(s -> s, s -> 1,
(i, j) -> i + j));
Run Code Online (Sandbox Code Playgroud)
非并发收集器是否可以安全地与并行流一起使用,还是在从并行流收集时只应使用并发版本?
当我注意到一些奇怪的东西时,我正在学习如何使用java 8流.
Arrays.stream() 有浮动数组的所有方法:
Arrays.stream(int[]) : IntStreamArrays.stream(long[]) : LongStreamArrays.stream(double[]) : DoubleStream类似地,有int,double等的Stream实现,但不是浮点数:
IntStreamLongStreamDoubleStream这有什么理由吗?
使用浮点流的推荐方法是什么?
我试图将a转换double[]为float[]使用Java 8 lambda演算.到目前为止,我刚刚创建了一个应该修改的玩具方法.试图找到转换原始数组的帮助.大多数情况下,是否有任何方法可以摆脱guava转换,因为转换为List和返回对于大型数组来说太重了.
import com.google.common.primitives.Floats;
public static float[] doubleToFloat(double[] vector) {
Float[] f = Arrays.stream(vector).<Float>mapToObj(x -> (float) x).toArray(Float[]::new);
return Floats.toArray(Arrays.asList(f));
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试使用Java 8 Stream API 将ArrayList包含的float值转换为原始浮点数组.到目前为止我尝试的是这样的:
List<Float> floatList = new ArrayList<Float>();
float[] floatArray = floatList.stream().map(i -> i).toArray(float[]::new)
Run Code Online (Sandbox Code Playgroud)