Skip to content



How to Convert a Stream to List in Java 8



18 August 2016no comments Java Posts, Java Posts, Java Tutorials

606 Total Views

convert-a-strem-to-list-in-java-8

In this tutorial you will see How to convert a Stream to a List using Collectors.toList in Java 8.

package com.latest_turorial.java8;

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

public class StreamToList {

    public static void main(String[] args) {

        Stream<String> language = Stream.of("java", "php", "asp.net");

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

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

    }
}
Output:

java
php
asp.net

Here you Filter a number 4 and convert it to a List.

package com.latest_tutorial.java8;

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

public class StreamToList {

    public static void main(String[] args) {

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

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

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


    }
}
output

1
2
3
5

References

  1. Java 8 Streams filter examples
  2. Java 8 Collectors JavaDoc
  3. Mkyong

 

Spread The Love, Share Our Article

  • Delicious
  • Digg
  • Newsvine
  • RSS
  • StumbleUpon
  • Technorati
  • Twitter

Related Posts

Facebook Iconfacebook like buttonTwitter Icontwitter follow buttonFollow Us
Follow

Get every new post delivered to your Inbox

Join other followers

%d bloggers like this: