Friday, 20 October 2017

How to convert streams to other data sources | Streams in Java 8


Click here to watch in Youtube : 
https://www.youtube.com/watch?v=mUM-ZbtrbXI&list=UUhwKlOVR041tngjerWxVccw

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

/**
 * Convert Streams to Other DataStructures
 * 
 * Get Collections using stream.collect(Collectors.toList()).
 */
public class StreamDemo1
{
    public static void main(String[] args)
    {
        Stream<String> stream = Stream.of("Peter", "John", "Ram");
        
        List<String> nameList = stream.collect(Collectors.toList());

        System.out.println(nameList);
    }

}
Output
[Peter, John, Ram]

StreamDemo2.java
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

/**
 * Convert Streams to Other DataStructures
 * 
 * Get arrays using stream.toArray(EntryType[]::new)
 */
public class StreamDemo2
{
    public static void main(String[] args)
    {
        List<Integer> numberList = new ArrayList<>();
        numberList.add(1);
        numberList.add(2);
        numberList.add(3);
        numberList.add(4);
        
        Stream<Integer> stream = numberList.stream();
        Integer[] evenArray = stream.filter(i -> i % 2 == 0).toArray(Integer[]::new);
        for (Integer integer : evenArray)
        {
            System.out.println(integer);
        }
    }

}
Output
2
4

Click the below link to download the code:
https://sites.google.com/site/ramj2eev1/home/javabasics/StreamDemo_convert_list_array.zip?attredirects=0&d=1

Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/StreamDemo_convert_list_array

Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/a9fa8aa6476993bce8a79f4d0e8f1799d1d35a7f/BasicJava/StreamDemo_convert_list_array/?at=master

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • Kids Tutorial
  • No comments:

    Post a Comment