How to convert type of stream?

南楼画角 提交于 2019-12-06 15:25:29

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.

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.

Roland

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