How to convert type of stream?

橙三吉。 提交于 2019-12-08 06:19:55

问题


In addition to my question asked previously, that can be found here, How to combine list elements and find the price of largest combination

Instead of using Integer price, I am using String price,

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();

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!


回答1:


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();

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.




回答2:


Your problem is most probably here:

 s -> s.stream().map(Double.class::cast)

Your detailId is of type Long; but your are trying to convert that to a Double.




回答3:


Nearly a copy of my answer to your other question:

double maxPrice = details.stream()
  .mapToDouble(detail -> Stream.concat(Stream.of(detail.getDetailsId()),
                                       detail.getStackableDetails().stream())
    .flatMap(detailId -> details.stream()
      .filter(candidateDetail -> detailId.equals(candidateDetail.getDetailsId())))
    .map(Detail::getPrice)
    // the applied transformation function of your String price to double:
    .mapToDouble(Double::parseDouble) 
    .sum()
  )
  .max()
  .orElse(0.0);


来源:https://stackoverflow.com/questions/43757538/how-to-convert-type-of-stream

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!