简体   繁体   中英

Converting List<String> to TreeMap<Long, CustomClass> java lambda

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

Not tested, but should give you an idea.

例如:

final Map<Long, CustomClass> result = list.stream().collect(Collectors.toMap(Long::valueOf, ignore -> new CustomClass(), (x, y) -> y, TreeMap::new));

java.util.stream.Collectors#toMap(java.util.function.Function<? super T,? extends K>, java.util.function.Function<? super T,? extends U>, java.util.function. BinaryOperator,java.util.function.Supplier)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM