Search code examples
javalambdajava-8exchangewebservices

Using forEach in Java 8


I am trying to use forEach() method in Java 8.

My code looks like the following:

String c = service.resolveName("Example").forEach((NameResolution c->{Implementation}));

Here, forEach method is not executed for a List<String>. It's executed for a List<NameResolution>. Now, when I am trying to iterate obj of NameResolution, it still shows the String operation.

Can we use forEach() for Lists of non-String values? If yes, then how?


Solution

  • Yes, you can, but you should fix your lambda expression to :

    service.resolveName("Example").forEach((NameResolution c)->{...});
    

    This is assuming service.resolveName("Example") returns a List<NameResolution> (or some other Collection<NameResolution>).

    Note the forEach doesn't return anything.