java - IntStream.range().filter.mapToObj().collect 究竟是什么意思
问题描述
我是 Java 新手,在阅读这些特定的代码行时卡住了:
private static void checkPrice(final List<String> prices) {
List<String> inputCountryCodes = IntStream.range(0, prices.size())
.filter(index -> (index % 2 == 0))
.mapToObj(prices::get)
.collect(Collectors.toList());
List<String> distinctInputCountryCodes = inputCountryCodes.stream()
.distinct()
.collect(Collectors.toList());
}
任何人都可以解释一下这些特定代码行在这里做什么的代码的 para1 和 para2 吗?
解决方案
IntStream.range(0, prices.size())
它生成一个从 0 到奖品列表大小(不包括)的整数流。所以假设你prices.size()
等于 3 那么InputStream将发出 0, 1, 2
filter(index -> (index % 2 == 0))
然后,它的中间操作将过滤由InputStream
基础产生的那些数字,该数字将使用 2 进行建模。即检查数字是否为偶数。如果它甚至会被进一步传递或者被丢弃
mapToObj(prices::get)
mapToObj它采用过滤后的数字(偶数)并使用它从prices
. 所以上面的代码就像
mapToObj(num -> {
String item = prices.get(num);
return item;
})
collect(Collectors.toList());
mapToObj
从into收集结果List<String>
因此,您List<String> inputCountryCodes
将包含prices
索引为偶数的项目。
inputCountryCodes.stream().distinct()
这将从您的类型中创建一个Stream ,
然后仅从中取出不同的项目。例如,如果您有, , ,
它将导致,inputCountryCodes
List<String>
inputCountryCodes
item1
item2
item2
item1
item1
item2
collect(Collectors.toList());
然后从不同的地方收集结果List<String>
所以最后你的List<String> distinctInputCountryCodes
遗嘱包含来自prices
a) whose index is an even number
b) And items are distinct
推荐阅读
- python - numpy set_printoptions 不适用于 numpy.ma 数组
- sql - 如果不存在则插入,否则更新然后在旧记录上设置标志
- python - Python中的Flask分页帮助
- java - 如何将名称值对作为列表传递给java中的方法
- iphone - 未调用方法“场景(_:openURLContexts :)”
- c# - .net mvc JWT 令牌更改 utf-8 字符
- python - Pandas dataframe.mean() 和切片错误的问题
- javascript - 如何从网页(js)打开 pwa 应用程序
- arrays - Scala:使用过滤器过滤数组与每个数组
- c# - WPF DataGrid 的左侧垂直滚动条:列宽未正确填充