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; } 
4
  • Who said it's possible? Commented Oct 17, 2017 at 0:56
  • 1
    i< str.length && i +1 < str.length is redundant. Commented Oct 17, 2017 at 0:57
  • 2
    a for loop would be a lot clean I feel Commented Oct 17, 2017 at 1:05
  • If you can use Guava stackoverflow.com/questions/9489384/… Commented Oct 17, 2017 at 17:16

2 Answers 2

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])); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ! very helpful
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} 

5 Comments

Thanks! solved my problem :)
Or IntStream.range(0, str.length/2).map(i -> i*2) which performs less operations, but on the other hand, won’t fail-fast when the array has an odd length.
@Holger OP's version doesn't fail on odd length either.
@shmosel: but I consider failing for malformed input a good thing.
@Holger I would generally agree, but it's hard to declare it malformed without more context.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.