I would like to convert the list to a map using only two string values as key values. Then, as values, just a list of strings containing items from odd or even index items from the input list. Here is the old fashion code:
Map<String, List<String>> map = new HashMap<>();
List<String> list = Arrays.asList("one", "two", "three", "four");
map.put("evenIndex", new ArrayList<>());
map.put("oddIndex", new ArrayList<>());
for (int i = 0; i < list.size(); i++) {
if(i % 2 == 0)
map.get("evenIndex").add(list.get(i));
else
map.get("oddIndex").add(list.get(i));
}
How to convert this code to Java 8 using threads to get this result?
{evenIndex=[one, three], oddIndex=[two, four]}
My current messy attempt requires changing the list items, but there definitely should be a better option.
List<String> listModified = Arrays.asList("++one", "two", "++three", "four");
map = listModified.stream()
.collect(Collectors.groupingBy(
str -> str.startsWith("++") ? "evenIndex" : "oddIndex"));
Or maybe someone will help me with this wrong decision?
IntStream.range(0, list.size())
.boxed()
.collect(Collectors.groupingBy( i -> i % 2 == 0 ? "even" : "odd",
Collectors.toMap( (i -> i ) , i -> list.get(i) ) )));
which return this:
{even={0=one, 2=three}, odd={1=two, 3=four}}