1

Suppose i have a list of string

List<String> fourthList = Arrays.asList("abc","def","ghi");

I want to convert it into Map like {1=abc,2=def,3=ghi}.

Collectors in java is not allowing to me do that as it accept method only in keyMapper .

2
  • This question has not been asked before or maybe i haven't found it. i was able to find convert list to map however in all the questions it mentioned user type variables .i was concerned about List of String type only . Commented Oct 16, 2019 at 13:05
  • Map<Integer, String> collect = IntStream.rangeClosed(0, fourthList.size() - 1) .boxed() .collect(Collectors.toMap(i -> i + 1, fourthList::get)); System.out.println(collect); Commented Nov 5, 2019 at 11:21

1 Answer 1

2

As Per Hadi J's comment (recommended) you can use use :

IntStream.rangeClosed(0, list.size() - 1) 
         .mapToObj(i -> new AbstractMap.SimpleEntry<Integer, String>(i + 1, list.get(i))) 
         .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Another way-around:

List<String> list = Arrays.asList("abc", "def", "ghi");

Converting List to Map<Integer, String> with key as integer and starting with 0...n:

AtomicInteger index = new AtomicInteger(0);
Map<Integer, String> map = list.stream()
            .collect(Collectors.toMap(s -> index.incrementAndGet(), Function.identity()));
map.forEach((l, m) -> System.out.println(l + "  " + m));

Output:

1  abc
2  def
3  ghi

I had done similar Map practices earlier this year, you can have a look: https://github.com/vishwaratna/ThatsHowWeDoItInJava8/blob/master/src/ListToMapWIthKeyAsInteger.java

Sign up to request clarification or add additional context in comments.

6 Comments

The problem is your use of a static variable k makes this non-thread-safe, among many other drawbacks.
Thread safety is not a concern for me now , anyways Its good catch.
Thanks Vishwa it worked , however i have doubt on toMap signature as it accepts Function as argument however here it is taking variable here
@RahulPyasi , you are right toMap signature accepts Function . Java lambda expressions are Java's first step into functional programming. A Java lambda expression is thus a function which can be created without belonging to any class.
@VishwaRatna This is clear explanation . thanks for info!
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.