目錄
二、Streams 中 filter(), findAny() 和 orElse()的用法
三、Streams中 filter() 和 map()的用法
五、strList.forEach(System.out::println);
Java8特性及應用16篇: https://blog.csdn.net/libusi001/article/details/105720935 一、stream().filter()
1、案例一
//原方法 public static void main(String[] args) { List<String> lines = Arrays.asList("spring", "hibernate", "neo4j"); List<String> result = getFilterOutput(lines, "neo4j"); for (String temp : result) { System.out.println(temp); } } private static List<String> getFilterOutput(List<String> lines, String filter) { List<String> result = new ArrayList<>(); for (String line : lines) { if (!filter.equals(line)) { result.add(line); } } return result; }
public static void main(String[] args) { List<String> lines = Arrays.asList("spring", "hibernate", "neo4j"); List<String> result = lines.stream() // 轉化爲一個流 .filter(line -> !"neo4j".equals(line)) // 排除 'String' .collect(Collectors.toList()); // 吧輸出流收集回List中 result.forEach(System.out::println); //輸出 : spring, hibernate }
2、案例二
package com.god.genius.baisc.jdk.jdk8.streamFilter.student; import java.time.LocalDate; import java.util.List; public class StudentInfo implements Comparable<StudentInfo> { //名稱 private String name; //性別 true男 false女 private Boolean gender; //年齡 private Integer age; //身高 private Double height; //出生日期 private LocalDate birthday; public StudentInfo(String name, Boolean gender, Integer age, Double height, LocalDate birthday){ this.name = name; this.gender = gender; this.age = age; this.height = height; this.birthday = birthday; } @Override public String toString(){ String info = String.format("%s\t\t%s\t\t%s\t\t\t%s\t\t%s",this.name,this.gender.toString(),this.age.toString(),this.height.toString(),birthday.toString()); return info; } public static void printStudents(List<StudentInfo> studentInfos){ System.out.println("[姓名]\t\t[性別]\t\t[年齡]\t\t[身高]\t\t[生日]"); System.out.println("----------------------------------------------------------"); studentInfos.forEach(s->System.out.println(s.toString())); System.out.println(" "); } @Override public int compareTo(StudentInfo ob) { return this.age.compareTo(ob.getAge()); //return 1; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getGender() { return gender; } public void setGender(Boolean gender) { this.gender = gender; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Double getHeight() { return height; } public void setHeight(Double height) { this.height = height; } public LocalDate getBirthday() { return birthday; } public void setBirthday(LocalDate birthday) { this.birthday = birthday; } }
測試代碼
package com.god.genius.baisc.jdk.jdk8.streamFilter.student; import java.time.LocalDate; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; /** * @author lisir */ public class Demo { public static void main(String[] args) { List<StudentInfo> list = new ArrayList<>(); list.add(new StudentInfo("李白", true, 18, 1.76, LocalDate.of(2001, 3, 23))); list.add(new StudentInfo("大喬", false, 18, 1.68, LocalDate.of(2001, 6, 3))); list.add(new StudentInfo("凱皇", true, 19, 1.82, LocalDate.of(2000, 3, 11))); list.add(new StudentInfo("小喬", false, 17, 1.61, LocalDate.of(2002, 10, 18))); //查詢所有英雄 StudentInfo.printStudents(list); //查找18歲的英雄 List<StudentInfo> collect = list.stream().filter(s -> s.getAge() == 19).collect(Collectors.toList()); StudentInfo.printStudents(collect); ////綜合查詢:查找身高在1.8米及以上且年齡小於19歲的英雄 List<StudentInfo> boys = list.stream().filter(s -> s.getGender() && s.getHeight() >= 1.66 && s.getAge() < 19).collect(Collectors.toList()); //輸出查找結果 StudentInfo.printStudents(boys); list.forEach(s -> System.out.println(s.toString())); list.stream().forEach(s->System.out.println(s.toString())); } }
二、Streams 中 filter(), findAny() 和 orElse()的用法
public static void main(String[] args) { List<User> userList = Arrays.asList( new User("mkyong", 30), new User("jack", 20), new User("lawrence", 40) ); User result = getStudentByName(userList, "jack"); System.out.println(result); } private static User getStudentByName(List<User> userList, String name) { User result = null; for (User temp : userList) { if (name.equals(temp.getName())) { result = temp; } } return result; }
public static void main(String[] args) { List<User> userList = Arrays.asList( new User("張三", 30), new User("李四", 20), new User("Enoch", 40) ); User result1 = userList.stream() // 轉化爲流 .filter(x -> "Enoch".equals(x.getName())) // 只過濾出"Enoch" .findAny() // 如果找到了就返回 .orElse(null); // 如果找不到就返回null System.out.println(result1); User result2 = userList.stream() .filter(x -> "Enoch".equals(x.getName())) .findAny() .orElse(null); System.out.println(result2); }
public static void main(String[] args) { List<User> userList = Arrays.asList( new User("張三", 30), new User("李四", 20), new User("Enoch", 40) ); User result1 = userList.stream() .filter((p) -> "李四".equals(p.getName()) && 20 == p.getAge()) .findAny() .orElse(null); System.out.println("result 1 :" + result1); //或者這樣寫 User result2 = userList.stream() .filter(p -> "Enoch".equals(p.getName()) && 20 == p.getAge()).findAny() .orElse(null); System.out.println("result 2 :" + result2); }
三、Streams中 filter() 和 map()的用法
public static void main(String[] args) { List<User> userList = Arrays.asList( new User("張三", 30), new User("李四", 20), new User("Enoch", 40) ); String name = userList.stream() .filter(x -> "Enoch".equals(x.getName())) .map(User::getName) //把流轉化爲String,這裏其實就是 //把一個新的事物轉爲另外一種事物了,類型得到了轉換 .findAny() .orElse(""); System.out.println("name : " + name); List<String> collect = userList.stream() .map(User::getName) .collect(Collectors.toList()); collect.forEach(System.out::println); }
四、Streams中 forache
filterLists.stream().forEach(s -> System.out.println(s));
Stream.generate(random).limit(10).forEach(System.out::println);//可傳入方法
roster.stream().parallel().filter(p1.negate()).forEach(p -> t.test(p));//也可以實現接口
五、strList.forEach(System.out::println);
// 創建出一個數組 List<String> strList = Arrays.asList("YangHang", "AnXiaoHei", "LiuPengFei"); strList.forEach(System.out::println);
首先, 我們看一下是java.lang.Iterable<T>下的一個默認方法forEach調用的,一看到這個function包下面的被@FunctionalInterface註解聲明的Consumer<T>接口, 瞬間就瞭然了, 這不又是函數式編程搞的鬼麼?
現在的問題應該很明朗了, System.out::println這段代碼其實就是Consumer<T>接口的一個實現方式啊。具體是怎麼實現,如下代碼。
@Test public void testDemo2() { List<String> strList = Arrays.asList("YangHang", "AnXiaoHei", "LiuPengFei"); strList.forEach(x -> { System.out.println(x); }); }
然後, 我們驚喜的發現和上面的代碼運行結果是一制的, 我們基本上可以斷定, 上面那種寫法是下面這種的一種縮寫形式。 就是把你遍歷出來的每一個對象都用來去調用System.out(也就是PrintStream類的一個實例)的println方法。
最後, 大家是不是有一個想法, 想自己寫一個Consumer<T>接口的實現類, 讓foreach調用一下。public class PrintUtil { /** * 對要遍歷的元素添加add操作 */ public void addString(String x) { System.out.println(x + "add"); } }
然後, 我們這麼來玩
@Test public void testDemo3() { List<String> strList = Arrays.asList("YangHang", "AnXiaoHei", "LiuPengFei"); strList.forEach(new PrintUtil()::addString); }
運行一下, 果然可以的。
但是發現, 如果是靜態方法的時候必須得用類名雙冒號靜態方法, 這估計是語法的一種, 注意就好。
Java8 之stream()操作
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.