Java 8 – Filter a null value from a Stream - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
Java 8

Java 8 – Filter a null value from a Stream

Review a Stream containing null values.
Java8Examples.java
package com.mycareerrepublic.java8;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8Examples {

public static void main(String[] args) {

Stream<String> language = Stream.of("java", "python", "node", null, "ruby", null, "php");

List<String> result = language.collect(Collectors.toList());

result.forEach(System.out::println);

}
}
output
java
python
node
null // <--- NULL
ruby
null // <--- NULL
php

Solution

To solve it, uses Stream.filter(x -> x!=null)
Java8Examples.java
package com.mycareerrepublic.java8;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8Examples {

public static void main(String[] args) {

Stream<String> language = Stream.of("java", "python", "node", null, "ruby", null, "php");

//List<String> result = language.collect(Collectors.toList());

List<String> result = language.filter(x -> x!=null).collect(Collectors.toList());

result.forEach(System.out::println);


}
}
output
java
python
node
ruby
php
Alternatively, filter with Objects::nonNull
import java.util.List;

List<String> result = language.filter(Objects::nonNull).collect(Collectors.toList());

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.