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
How to Update Each Element in a List in Java 8 Using Stream API
How to Check If a Date Is Within a Certain Range
Why Is My Spring @Autowired Field Null
Java Socket Api: How to Tell If a Connection Has Been Closed
How to Do a Limit Query in Jpql or Hql
Calling Method That Exists in Child Classes But Not in Parent Class
Comparing Two List by Using Java8 Matching Methods
Java.Io.Filenotfoundexception: (Access Is Denied)
How to Pass the Same Object Across Multiple Classes Java
Forwarding the Request from One Jsp to Another Jsp With All Request Parameters
Spring Boot - How to Get Running Port and Ip Address
How to Take Input as String With Spaces in Java Using Scanner
Prevent Multiple Login Using the Same User Name and Password
Spring Junit: How to Mock Autowired Component in Autowired Component
Field Required a Bean Which Could Not Be Found in Springboot
Mockito How to Mock Only the Call of a Method of the Superclass