首页 > 解决方案 > 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 吗?

标签: javalistdictionary

解决方案


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 , 然后仅从中取出不同的项目。例如,如果您有, , , 它将导致,inputCountryCodesList<String>inputCountryCodesitem1item2item2item1item1item2

collect(Collectors.toList());

然后从不同的地方收集结果List<String>

所以最后你的List<String> distinctInputCountryCodes遗嘱包含来自prices

a) whose index is an even number

b) And items are distinct

推荐阅读