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!
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
.
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