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 .
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 .
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