I’m trying to convert a List<String>
to a TreeMap<Long, CustomClass>
The key is the same as the list items but just parsed to Long
, the value is just a call to new CustomClass()
. How can I achieve this using lambda functions?
List<String> list = List.of("1","2","3"); TreeMap<Long, CustomClass> resultMap = list.stream() .collect(Collectors.toMap(i -> Long.parseLong(i), v -> new CustomClass()));
the above code errors out, with the following error,
Required type: TreeMap<Long,CustomClass> Provided: Map<Object,Object> no instance(s) of type variable(s) K, U exist so that Map<K, U> conforms to TreeMap<Long, CustomClass>
Advertisement
Answer
For example:
final Map<Long, CustomClass> result = list.stream().collect(Collectors.toMap(Long::valueOf, ignore -> new CustomClass(), (x, y) -> y, TreeMap::new));