Lambda Expression Using Foreach Clause

Java 8 Lambda Stream forEach with multiple statements

Forgot to relate to the first code snippet. I wouldn't use forEach at all. Since you are collecting the elements of the Stream into a List, it would make more sense to end the Stream processing with collect. Then you would need peek in order to set the ID.

List<Entry> updatedEntries = 
entryList.stream()
.peek(e -> e.setTempId(tempId))
.collect (Collectors.toList());

For the second snippet, forEach can execute multiple expressions, just like any lambda expression can :

entryList.forEach(entry -> {
if(entry.getA() == null){
printA();
}
if(entry.getB() == null){
printB();
}
if(entry.getC() == null){
printC();
}
});

However (looking at your commented attempt), you can't use filter in this scenario, since you will only process some of the entries (for example, the entries for which entry.getA() == null) if you do.

How to use if-else logic in Java 8 stream forEach

Just put the condition into the lambda itself, e.g.

animalMap.entrySet().stream()
.forEach(
pair -> {
if (pair.getValue() != null) {
myMap.put(pair.getKey(), pair.getValue());
} else {
myList.add(pair.getKey());
}
}
);

Of course, this assumes that both collections (myMap and myList) are declared and initialized prior to the above piece of code.


Update: using Map.forEach makes the code shorter, plus more efficient and readable, as Jorn Vernee kindly suggested:

    animalMap.forEach(
(key, value) -> {
if (value != null) {
myMap.put(key, value);
} else {
myList.add(key);
}
}
);

How to OR a foreach looped linq lambda expression

You can use the .Any() method:

result = result.Where(c => keywords.Any(k => c.Title.Contains(k)));

You can further filter out words less than 5 characters like it seems you might want:

result = result.Where(c => keywords.Where(k => k.Length > 4).Any(k => c.Title.Contains(k)));

Although it would be more efficient to do it once when constructing your keywords array:

var keywords = item.Split('-').Where(k => k.Length > 4).ToArray();

Using the ternary operator with a lambda expression inside a foreach in C#

Try:

Array.ForEach(worldState, x =>  Console.WriteLine(x ? "T" : "F") );

The ternary function requires a value be returned, so in this case your T or F should be returned to the WriteLine method.

Personally, I think a foreach or for loop would be cleaner and more efficient.

foreach(bool bVal in Array) { Console.WriteLine(bVal ? "T" : "F"); }

or

for(i = 0; i < Array.Length; i ++) { Console.WriteLine(Array[i] ? "T" : "F"); }

Else clause in lambda expression

You could collect the result after the filter operation into a list instance and then check the size before operating on it.

List<Path> resultSet = Files.walk(rootDir)
.filter(matcher::matches)
.collect(Collectors.toList());
if(resultSet.size() > 0){
resultSet.forEach(Start::modify);
}else {
// do something else
}

Alternatively, you could do something like this:

if(Files.walk(rootDir).anyMatch(matcher::matches)) {
Files.walk(rootDir)
.filter(matcher::matches)
.forEach(Start::modify);
}else {
// do something else
}

Break or return from Java 8 stream forEach?

If you need this, you shouldn't use forEach, but one of the other methods available on streams; which one, depends on what your goal is.

For example, if the goal of this loop is to find the first element which matches some predicate:

Optional<SomeObject> result =
someObjects.stream().filter(obj -> some_condition_met).findFirst();

(Note: This will not iterate the whole collection, because streams are lazily evaluated - it will stop at the first object that matches the condition).

If you just want to know if there's an element in the collection for which the condition is true, you could use anyMatch:

boolean result = someObjects.stream().anyMatch(obj -> some_condition_met);


Related Topics



Leave a reply



Submit