vesnaves
vesnaves

Reputation: 55

how to make forEach

I have a for:

Map<String, Integer> map = new LinkedHashMap<>();       
for (String o: gamma)
   map.merge(o, 1, (a, b) -> a + b);

I need to make forEach like this:

gamma.forEach(e -> map.merge(e, 1, (a, b) -> a + b));

But then I do like this I received a message: Cannot invoke forEach(( e) -> {}) on the array type String[]

What I am doing wrong? How to do this forEach?

Upvotes: 1

Views: 636

Answers (3)

Nicholas K
Nicholas K

Reputation: 15423

Another approach :

Arrays.stream(gamma).forEach(e -> map.merge(e, 1, (a, b) -> a + b));

Upvotes: 0

drowny
drowny

Reputation: 2147

Do it like this ;

Arrays.asList(gamma).forEach(e -> map.merge(e, 1, (a, b) -> a + b));

Your gamma is String array, convert to list to foreach on this.

Upvotes: 0

Dici
Dici

Reputation: 25950

Just use Stream.of: Stream.of(gamma).forEach(e -> map.merge(e, 1, (a, b) -> a + b));

And use Google for your next problem!

Upvotes: 3

Related Questions