将列表<String>转换为 TreeMap<Long、CustomClass> java lambda



我正试图将List<String>转换为TreeMap<Long, CustomClass>,关键与列表项相同,但只是解析为Long,该值只是对new CustomClass()的调用。我如何使用lambda函数实现这一点?

List<String> list = List.of("1","2","3");
TreeMap<Long, CustomClass> resultMap = list.stream()
.collect(Collectors.toMap(i -> Long.parseLong(i), v -> new CustomClass()));

上面的代码出错了,下面的错误,

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>

例如:

final Map<Long, CustomClass> result = list.stream().collect(Collectors.toMap(Long::valueOf, ignore -> new CustomClass(), (x, y) -> y, TreeMap::new));
List<String> list = List.of("1","2","3");
HashMap<Long, CustomClass> map =
list.stream()        
.collect(
Collectors.toMap(i->Long.parseLong(i),v->new CustomClass()));
TreeMap<Long, CustomClass> resultMap =new TreeMap(map);

没有测试,但应该给你一个想法。

最新更新