Java 8 – Convert a Stream to List - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
Java 8

Java 8 – Convert a Stream to List

Java 8 – Convert a Stream to List

A Java 8 example to show you how to convert a Stream to a List via Collectors.toList
Java8Example1.java
package com.mycareerrepublic.java8;

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

public class Java8Example1 {

public static void main(String[] args) {

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

//Convert a Stream to List
List<String> result = language.collect(Collectors.toList());

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

}
}
output
java
python
node
Yet another example, filter a number 3 and convert it to a List.
Java8Example2.java
package com.mycareerrepublic.java8;

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

public class Java8Example2 {

public static void main(String[] args) {

Stream<Integer> number = Stream.of(1, 2, 3, 4, 5);

List<Integer> result2 = number.filter(x -> x!= 3).collect(Collectors.toList());

result2.forEach(x -> System.out.println(x));


}
}
output
1
2
4
5

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.