2

I have the below code to implement the requirement, but couldn't solve using stream , I'm not sure how to increment i in pipeline

String[] str = {"a","b","c","d","e","f"};
    Map<String, String> strMap = new HashMap<>();
    int i = 0;
    while(i< str.length && i +1 < str.length) {
        strMap.put(str[i],str[i+1]);
        i +=2;          
    } 
shmosel
  • 49,289
  • 6
  • 73
  • 138
prisesh
  • 77
  • 5

2 Answers2

4

You can't do it with a simple stream of str, but you can mimic your loop with an index stream:

Map<String, String> strMap = IntStream.range(0, str.length - 1)
        .filter(i -> i % 2 == 0)
        .boxed()
        .collect(Collectors.toMap(i -> str[i], i -> str[i + 1]));
Naman
  • 27,789
  • 26
  • 218
  • 353
shmosel
  • 49,289
  • 6
  • 73
  • 138
3

It's a bit of a hack, but you could use an IntStream to generate your indices (between 0 and the length of the array), filter out the odd indices and then use a forEach to populate the strMap - like,

String[] str = { "a", "b", "c", "d", "e", "f" };
Map<String, String> strMap = new HashMap<>();
IntStream.range(0, str.length).filter(i -> i % 2 == 0)
        .forEach(i -> strMap.put(str[i], str[i + 1]));
System.out.println(strMap);

Which outputs (as requested)

{a=b, c=d, e=f}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249