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 .

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
  • 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 . – Rahul Pyasi Oct 16 '19 at 13:05
  • Map collect = IntStream.rangeClosed(0, fourthList.size() - 1) .boxed() .collect(Collectors.toMap(i -> i + 1, fourthList::get)); System.out.println(collect); – user2173372 Nov 05 '19 at 11:21

1 Answers1

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

MC Emperor
  • 22,334
  • 15
  • 80
  • 130
Vishwa Ratna
  • 5,567
  • 5
  • 33
  • 55
  • 2
    The problem is your use of a static variable `k` makes this non-thread-safe, among many other drawbacks. – DodgyCodeException Oct 16 '19 at 10:28
  • 1
    Thread safety is not a concern for me now , anyways Its good catch. – Rahul Pyasi Oct 16 '19 at 10:49
  • 1
    Thanks Vishwa it worked , however i have doubt on toMap signature as it accepts Function as argument however here it is taking variable here – Rahul Pyasi Oct 16 '19 at 10:50
  • 1
    @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.* – Vishwa Ratna Oct 16 '19 at 10:53
  • 1
    @VishwaRatna This is clear explanation . thanks for info! – Rahul Pyasi Oct 16 '19 at 13:01
  • `IntStream.range(0, list.size()).mapToObj(i -> new AbstractMap.SimpleEntry<>(i + 1, list.get(i)))...` could have read bettter. – Naman Oct 17 '19 at 06:00