Click here to watch in Youtube :
https://www.youtube.com/watch?v=PdbpO6Czmp8&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge
How to filter the List of Names using Java 8 Stream | Java 8 streams tutorial | Streams in Java 8 |
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class FilterDemo { public static void main(String[] args) { List<String> namesList = Arrays.asList("Ram", "Peter","Pradeep", "Steve"); List<String> filteredNameList = getFilterOutput(namesList, "P"); for (String name : filteredNameList) { System.out.println(name); } } private static List<String> getFilterOutput(List<String> namesList, String filter) { List<String> filteredNameList = new ArrayList<>(); for (String name : namesList) { if (name.startsWith("P")) { filteredNameList.add(name); } } return filteredNameList; } }Output
Peter PradeepStreamDemo1.java
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class StreamDemo1 { public static void main(String[] args) { List<String> namesList = Arrays.asList("Ram", "Peter","Pradeep", "Steve"); /* * Convert list to stream. * * Returns a sequential Stream with this collection as its * source. */ Stream<String> stream = namesList.stream(); /* * filters the name, starts with "P". * * Returns a stream consisting of the elements of this stream * that match the given predicate. */ stream = stream.filter(name -> name.startsWith("P")); /* * Collect the output and convert streams to a List. * * Performs a mutable reduction operation on the elements of * this stream using a Collector. */ List<String> filteredNameList = stream.collect(Collectors.toList()); filteredNameList.forEach(System.out::println); } }Output
Peter PradeepStreamDemo2.java
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamDemo2 { public static void main(String[] args) { List<String> namesList = Arrays.asList("Ram", "Peter","Pradeep", "Steve"); List<String> filteredNameList = namesList.stream() //convert list to stream .filter(name -> name.startsWith("P")) //filters the name, starts with "P". .collect(Collectors.toList()); //collect the output and convert streams to a List filteredNameList.forEach(System.out::println); } }Output
Peter PradeepRefer:
https://docs.oracle.com/javase/8/docs/api/index.html?java/util/stream/Stream.html
https://docs.oracle.com/javase/8/docs/api/index.html?java/util/function/Predicate.html
https://sites.google.com/site/ramj2eev1/home/javabasics/StreamDemo_nameList_filter_App.zip?attredirects=0&d=1
Github Link:
https://github.com/ramram43210/Java/tree/master/BasicJava/StreamDemo_nameList_filter_App
Bitbucket Link:
https://bitbucket.org/ramram43210/java/src/c8efc47167637d9bcc657c3cee2ad048e22a2b17/BasicJava/StreamDemo_nameList_filter_App/?at=master
See also:
No comments:
Post a Comment