参考前提 Java stream 步骤而不破坏流管道?
Reference antecedent Java stream step without breaking the stream pipeline?
我是函数式编程的新手,我正在努力变得更好。
目前,我正在试验一些具有以下基本形式的代码:
private static int myMethod(List<Integer> input){
Map<Integer,Long> freq = input
.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
return (int) freq
.keySet()
.stream()
.filter(key-> freq.containsKey(freq.get(key)))
.count();
}
首先使用哈希图获取列表中每个数字的频率。接下来,我们总结其值也作为键存在于映射中的键的数量。
我不喜欢的是这两个流需要彼此分开存在,其中 HashMap 由一个流创建,仅供另一个流立即且独占地使用。
有没有办法将其合并为一个流?我在想这样的事情:
private static int myMethod(List<Integer> input){
return (int) input
.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.keySet()
.stream()
.filter(key-> freq.containsKey(freq.get(key)))
.count();
}
但这里的问题是没有频率图可供参考,因为它被用作管道的一部分,所以过滤器不能做它需要做的事情。
总而言之,我不喜欢它收集到哈希映射然后才转换回键集。有没有办法将此操作“简化”(双关语意)
- 不会在流和 hashmap 之间来回切换
- 以无需在管道之前声明单独映射的方式引用自身。
谢谢!
你的 keySet 只不过是一个由你的 input
组成的 HashSet
。因此,您应该使用临时存储:
Set<Integer> freq = new HashSet<>(input);
并进一步计数,根据单个流管道中的值进行过滤,如
return (int) input
.stream()
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()))
.values() // just using the frequencies evaluated
.stream()
.filter(count -> freq.contains(count.intValue()))
.count();
我是函数式编程的新手,我正在努力变得更好。
目前,我正在试验一些具有以下基本形式的代码:
private static int myMethod(List<Integer> input){
Map<Integer,Long> freq = input
.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
return (int) freq
.keySet()
.stream()
.filter(key-> freq.containsKey(freq.get(key)))
.count();
}
首先使用哈希图获取列表中每个数字的频率。接下来,我们总结其值也作为键存在于映射中的键的数量。
我不喜欢的是这两个流需要彼此分开存在,其中 HashMap 由一个流创建,仅供另一个流立即且独占地使用。
有没有办法将其合并为一个流?我在想这样的事情:
private static int myMethod(List<Integer> input){
return (int) input
.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.keySet()
.stream()
.filter(key-> freq.containsKey(freq.get(key)))
.count();
}
但这里的问题是没有频率图可供参考,因为它被用作管道的一部分,所以过滤器不能做它需要做的事情。
总而言之,我不喜欢它收集到哈希映射然后才转换回键集。有没有办法将此操作“简化”(双关语意)
- 不会在流和 hashmap 之间来回切换
- 以无需在管道之前声明单独映射的方式引用自身。
谢谢!
你的 keySet 只不过是一个由你的 input
组成的 HashSet
。因此,您应该使用临时存储:
Set<Integer> freq = new HashSet<>(input);
并进一步计数,根据单个流管道中的值进行过滤,如
return (int) input
.stream()
.collect(Collectors.groupingBy(Function.identity(),
Collectors.counting()))
.values() // just using the frequencies evaluated
.stream()
.filter(count -> freq.contains(count.intValue()))
.count();