英文:
Java stream question, mapToInt and average method
问题
为什么我可以在一个上调用 average() 方法,但在另一个上却不能?它们不应该是等效的吗?
示例1 - 能够运行
List<String> stringList = new ArrayList<>();
stringList.add("2");
stringList.add("4");
stringList.add("6");
// 字符串数组 ("2", "4", "6")
averageValue = stringList.stream()
.mapToInt(s -> Integer.valueOf(s))
.average()
.getAsDouble();
示例2 - 无法编译(删除了 mapToInt 调用,因为已经传递了 Integer 流)
List<Integer> IntegerList = new ArrayList<>();
IntegerList.add(2);
IntegerList.add(4);
IntegerList.add(6);
averageValue = IntegerList.stream()
.average()
.getAsDouble();
问题是,既然我已经传递了整数流,为什么我需要调用 mapToInt 方法呢?
英文:
Why can I call average() method on one but not on the other? Shouldn't they be equivalent?
example 1 - works
List<String> stringList = new ArrayList<>();
stringList.add("2");
stringList.add("4");
stringList.add("6");
// String array ("2","4", "6"
averageValue = stringList.stream()
.mapToInt(s -> Integer.valueOf(s))
.average()
.getAsDouble();
example 2 - doesn't compile (deleted mapToInt call because already passing Integer stream)
List<Integer> IntegerList = new ArrayList<>();
IntegerList.add(2);
IntegerList.add(4);
IntegerList.add(6);
averageValue = IntegerList.stream()
.average()
.getAsDouble();
Question, is why do I need to call mapToInt method when Im already passing it a stream of Integers?
答案1
得分: 9
有两种不同的类型:一个 Stream<Integer> 和一个 IntStream。
Java 的泛型不能只适用于某些泛型上的方法。例如,它不能只有 Stream<Integer>.average() 而不同时也有 Stream<PersonName>.average(),尽管人名的平均值没有意义。
因此,Stream 有一个 mapToInt 方法,将其转换为 IntStream,然后提供了 average() 方法。
英文:
There are two different types: a Stream<Integer> and an IntStream.
Java's generics can't have methods that only apply on some generics. For example, it couldn't have Stream<Integer>.average() and not also have Stream<PersonName>.average(), even though the average person name doesn't make sense.
Therefore, Stream has a mapToInt method that converts it into an IntStream, which then provides the average() method.
答案2
得分: 4
IntStream提供了average()方法,因此要使用它,您需要通过使用mapToInt方法将Stream<Integer>转换为IntStream。
英文:
IntStream provides average() method, so to use it you need to convert Stream<Integer> to IntStream by using mapToInt method.
专注分享java语言的经验与见解,让所有开发者获益!

评论