How to Use If-Else Logic in Java 8 Stream Foreach

If/else representation with stream and Java 8

This is a perfect example of when to use the Optional#orElse or the Optional#orElseThrow method(s). You want to check if some condition is met so you filter, trying to return a single result. If one does not exist, some other condition is true and should be returned.

try {
Parser parser = parsers.stream()
.filter(p -> p.canParse(message))
.findAny()
.orElseThrow(NoParserFoundException::new);

// parser found, never null
parser.parse();
} catch (NoParserFoundException exception) {
// cannot find parser, tell end-user
}

How to Apply if/else logic in stream API in java.?

regardless of the original question, order of order columns is significant.
by splitting into ascending and descending columns you change the order of order columns!

So, what you need to do is stream the original list and add the columns - each with its own direction:

orderByQuery = ORDER_BY + 
listOfSortCriteria.stream().map(e->e.getSortColumn() + " " + (e->e.getSortAscending().equals("true") ? "ASC":"DESC"))
.collect(Collectors.joining(","));

Replacing if-else within 'for' loops with Java-8 Streams

It sounds like you can just use map with a condition:

List<String> list2 = list
.stream()
.map(str -> someCondition(str) ? doSomething(str) : doSomethingElse(str))
.collect(Collectors.toList());

Short but complete example mapping short strings to lower case and long ones to upper case:

import java.util.*;
import java.util.stream.*;

public class Test {

public static void main(String[] args) {
List<String> list = Arrays.asList("abC", "Long Mixed", "SHORT");
List<String> list2 = list
.stream()
.map(str -> str.length() > 5 ? str.toUpperCase() : str.toLowerCase())
.collect(Collectors.toList());
for (String result : list2) {
System.out.println(result); // abc, LONG MIXED, short
}
}
}


Related Topics



Leave a reply



Submit