Filter Values Only If Not Null Using Lambda in Java8

Apply Filter if given value is not null

Either do it in two steps:

Stream<Student> studentStream = students.stream();
if (studentName != null) {
studentStream = studentStream.filter(s -> s.getName().equals(studentName));
}
studentsList = studentStream.collect(Collectors.toList());

Or add the null check into the filter itself:

studentsList = students.stream()
.filter(s -> studentName == null || s.getName().equals(studentName))
.collect(Collectors.toList());

Filter out null values in Java 8 stream filter expression so exception is not thrown

The attributes such as the billingMethod, whenever it is possibly null inside the List, it should still work for comparison to get distinct values.
On the other hand, comparing them with some other String constant can be solved in the manner the user FilipRistic suggested.

But, when it is about objects which could be possibly null and you want to access the inner attributes further down safely, you can make use of Optional and chain the accessors. For a sample amongst those, while you want to access the numberCode of your destination which could possibly be null, you can have an accessor in PurchasedTripSegment class to expose this:

Optional<Integer> getDestinationCode() {
return Optional.ofNullable(this.getDestination()) // empty for 'null'
.map(Node::getNumberCode);
}

With similar changes for other accessors, your overall code would update and change to something like:

filteredList = purchasedTripSegments.stream()
.filter(segment -> PurchasedVendorType.RAIL.equals(segment.getVendorType()))
.filter(distinctByKey(segment -> Arrays.asList(segment.getBillingMethod(),
segment.getOriginCode(), segment.getDestinationCode(),
segment.getStopOffLocationCode())))
.filter(segment -> segment.getBillingMethod().equalsIgnoreCase(BILLING_METHOD_LOCAL) ||
(segment.getBillingMethod().equalsIgnoreCase(BILLING_METHOD_RULE) &&
segment.getDestinationCode().equals(segment.getStopOffLocationCode())))
.collect(Collectors.toList());

Filter/ remove all null values of all elements using java8

As you said, null Objects can be filtered. So the problem is objects of unknown class with null fields, like Employee, Manager, External. One could do it with reflection but that is ugly and slow. Better ensure in all those classes that they cannot have those null fields: Objects.requireNonNull. This ensures a fail-fast, so actually programmer testing will ensure correct code

class Employee {

public Employee(String name) {
Objects.requireNonNull(name);

When using some frameworks, one can use an annotation, like @NonNull for compile time code analysis.

    public Employee(@NonNull String name) {

And then one may guard to have the classes fields unassigned - when they are immutable - by final (constant fields):

    private final String name;

public Employee(String name) {
this.name = name; // Still name might be null, so:
Objects.requireNonNull(name);

Not a perfect solution.

Use lambda filter if element is not null otherwise ignore filter

Seems like your logic required is to check if any of the ProEffectiveDate is null just return the first element of the list, based on that you could do a check as :

ProList minFilteredRow;
if (proLists.stream().anyMatch(a -> a.getProEffectiveDate() == null)) {
minFilteredRow = proLists.get(0);
} else {
minFilteredRow = proLists.stream()
.filter(filteredRow)
.min(Comparator.comparing(ProList::getRecordNumber))
.orElse(null);
}

Java - Check Not Null/Empty else assign default value

If using JDK 9 +, use Objects.requireNonNullElse(T obj, T defaultObj)

How to filter elements which contains null references in java 8

Try this.

List<MyObject> parsedEvents = events.stream()
.filter(Objects::nonNull)
.filter(e -> Stream.of(e.foo(), e.bar(), e.baz())
.allMatch(Objects::nonNull))
.map(
e -> MyObject.builder()
.setFoo(e.foo())
.setBar(e.bar())
.setBaz(e.baz())
.build())
.collect(Collectors.toList());


Related Topics



Leave a reply



Submit