如何转换流的类型? [英] How to convert type of stream?
问题描述
除了之前提出的问题,可以在这里找到,
如何组合列表元素并找到最大组合的价格
In addition to my question asked previously, that can be found here, How to combine list elements and find the price of largest combination
而不是使用整数价格
,我使用字符串价格
,
List<Long> highest = details
.stream()
.map(d -> Stream.concat(Stream.of(d.getDetailId()), d.getStackableDetails().stream()).collect(Collectors.toList()))
.collect(Collectors.toMap(s -> s.stream().map(Double.class::cast).reduce(0D,
(left, right) -> left + Double.parseDouble(map.get(right).getPrice())),
s -> s.stream().collect(Collectors.toList()),
(left, right) -> right,
TreeMap::new))
.lastEntry().getValue();
但是在运行相同的时候我一直得到一个类强制转换异常。有人能告诉我为什么我无法投射Stream类型以及如何纠正它。谢谢!
But I keep getting a class cast exception while running the same. Can someone tell me why I'm not able to cast the Stream type and how I can rectify the same. Thanks!
推荐答案
我不太清楚你要做什么,但填充<$是没有意义的c $ c> TreeMap ,只是为了得到最后一个元素。获取最大元素是作为内在的 Stream
操作。
It’s not quite clear to me what you are trying to do, but there is no sense in populating a TreeMap
, just to get the last element. Getting the maximum element is provided as an intrinsic Stream
operation.
那么你在问题代码中所做的事情可以简化为
So what you are doing in the question’s code can be simplified to
List<Long> highest = details
.stream()
.map(d -> Stream.concat(Stream.of(d.getDetailId()), d.getStackableDetails().stream())
.collect(Collectors.toList()))
.max(Comparator.comparingDouble(s -> s.stream()
.mapToDouble(l -> Double.parseDouble(map.get((double)l).getPrice()))
.sum()))
.get();
这也可以通过简单地转换 Long $ c $来解决您的问题c>到
double
。这会将 Long
对象拆分为 long
值,执行扩展转换为 double
并将其加到 Double
中,用于 Map
查找。但是,建议不要将 Double
对象用作地图键。
This also fixes you problem by simply casting the Long
to double
. This will unbox the Long
object to a long
value, perform a widening conversion to double
and box it to a Double
for the Map
lookup. However, it’s not recommended to use Double
objects as map keys.
这篇关于如何转换流的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!