将Stream转换为IntStream [英] Convert Stream to IntStream

查看:78
本文介绍了将Stream转换为IntStream的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得我在这里想念一些东西.我发现自己在做以下事情

I have a feeling I'm missing something here. I found myself doing the following

private static int getHighestValue(Map<Character, Integer> countMap) {
    return countMap.values().stream().mapToInt(Integer::intValue).max().getAsInt();
}

我的问题是通过mapToInt(Integer::intValue)

是否有更好的转换方法?所有这些都是为了避免使用Stream中的max(),这需要传递Comparator,但是问题特别是关于StreamIntStream

Is there a better way of doing the conversion? all this is to avoid using max() from Stream, which requires passing a Comparator but the question is specifically on the convertion of Stream to IntStream

推荐答案

由于类型擦除,Stream实现不了解其元素的类型,因此无法为您提供任何简化的max操作,也不转换为IntStream方法.

Due to type erasure, the Stream implementation has no knowledge about the type of its elements and can’t provide you with neither, a simplified max operation nor a conversion to IntStream method.

在两种情况下,都需要分别使用ComparatorToIntFunction函数来使用Stream元素的未知引用类型来执行操作.

In both cases it requires a function, a Comparator or a ToIntFunction, respectively, to perform the operation using the unknown reference type of the Stream’s elements.

您要执行的操作的最简单形式是

The simplest form for the operation you want to perform is

return countMap.values().stream().max(Comparator.naturalOrder()).get();

考虑到自然顺序比较器被实现为单例的事实.因此,它是唯一可以被Stream实现 识别的比较器,前提是对Comparable元素进行了任何优化.如果没有这样的优化,由于其单例性质,它将仍然是具有最低内存占用的变体.

given the fact that the natural order comparator is implemented as a singleton. So it’s the only comparator which offers the chance of being recognized by the Stream implementation if there is any optimization regarding Comparable elements. If there’s no such optimization, it will still be the variant with the lowest memory footprint due to its singleton nature.

如果您坚持要进行StreamIntStream的转换,则无法提供ToIntFunction,并且对于Number::intValue类型的函数没有预定义的单例,因此请使用Integer::intValue已经是最好的选择.您可以改写i->i,它虽然较短,但随后只隐藏了取消装箱操作.

If you insist on doing a conversion of the Stream to an IntStream there is no way around providing a ToIntFunction and there is no predefined singleton for a Number::intValue kind of function, so using Integer::intValue is already the best choice. You could write i->i instead, which is shorter but just hiding the unboxing operation then.

这篇关于将Stream转换为IntStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆