And traversing the filter elements in the collection
- Using the element in a conventional manner to traverse the filter and the collection
cn.com.zq.demo01.Stream.test01.Stream Package; Import of java.util.ArrayList; Import java.util.List; / * * used in a conventional manner to traverse the filter and set * requirements: * 1, the first step in filtration, just to name beginning with "Zhang" * 2, the second step filtration just need to name the names of length 2 * * / public class Test01Stream { public static void main (String [] args) { // create a collection List, store names and filtered according to the requirements List <String> = new new nameList the ArrayList <> (); nameList.add ( "John Doe"); nameList.add ( "John Doe"); nameList.add ( "Wang Wu"); nameList.add ( "Zhao six"); nameList.add ( "Tianqi"); nameList.add ( "bastard"); nameList.add ( "Zhang Four"); nameList.add ( "Chi Master"); // use the traditional way to filter // 1, the first step filtration, you need only begin with the name of Zhang // need to create a new set of names after the first filter to store List <String> listA = new ArrayList < > (); for (String S: nameList) {// set with enhanced for loop is traversed if (s.startsWith ( "Zhang")) { listA.add (S); // add the result to the filter the new collection } } List <String> = new new listB the ArrayList <> (); for (String S: listA) { IF (s.length () == 2) { listB.add (S); } } for ( S String: listB) { of System.out.print (S + ""); // Double three four final filter results // final filter result sheets three four } } }
- Use the Stream flow traversing ways and filtration elements in the collection
cn.com.zq.demo01.Stream.test01.Stream Package; Import of java.util.ArrayList; Import java.util.List; / * * usage Stream flow through and the collection filter * requirements: 1, the first step in filtration , just to name "Chang" at the beginning of the 2, only the second step filtration, the name is the name of a length 2 * * / public class Test02Stream { public static void main (String [] args) { // create a collection List, store names and filtered according to the requirements List <String> = new new nameList the ArrayList <> (); nameList.add ( "John Doe"); nameList.add ( "John Doe"); nameList.add ( "Wang Wu"); nameList.add ( "Zhao six"); nameList.add ( "Tianqi"); nameList.add ( "bastard"); nameList.add ( "Zhang Four"); nameList.add ( "Chi Master"); // use Stream flow, to traverse the collection and filtration // 1, the first step filtration, need only begin with the name of "Zhang" // will be converted to a set of Stream flow a default method called directly interface Collection Stream nameList.stream (). filter (S-> s.startswith ( "Zhang")) .filter (S-> s.length () == 2) .forEach (S- > System.out.print (s + "") ); // output: three four sheets } }
Original: https: //blog.csdn.net/qq_41319058/article/details/90319707