sundar.sat84
sundar.sat84

Reputation: 579

How to convert List<Integer> to Map<Integer,String> using Java8 Streams

I have List and I want to convert to Map<Integer,String> using streams in java8.

Say for example : 
List<Integer> li = Arrays.asList(1,2,3);

Then want to convert to Map<Integer,String> like 
Map({1,"1"},{2,"2"},{3,"3"})

Upvotes: 0

Views: 497

Answers (2)

Sandip Jangra
Sandip Jangra

Reputation: 164

You can try below stuff and should work fine(Tested).

    List<Integer> li = Arrays.asList(1,2,3);
    Map<Integer, String> result =      
    li.stream().collect(Collectors.toMap(i -> i, i -> i.toString()));

Upvotes: 1

prost&#253; člověk
prost&#253; člověk

Reputation: 939

If you want map, there should be Key=Value pair, I assume you [{1,"1"}, {2,"2"}, {3,"3"}] want like this,

List<String> collect = li.stream()
                          .map(a -> "{"+a + ",\"" + a +"\"}")
                          .collect(Collectors.toList());

Upvotes: 0

Related Questions