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

Time:07-11

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()
        .map(x -> Long.parseLong(x))
        .collect(
            Collectors.toCollection(x -> new TreeMap<>()));

the above code errors out, I am not sure of the supplier param to be passed.

CodePudding user response:

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.

CodePudding user response:

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)

  • Related