1 package org.study2.java8.stream; 2 3 import org.junit.Test; 4 5 import java.util.*; 6 import java.util.stream.Collectors; 7 import java.util.stream.Stream; 8 9 /**10 * Java 8 – Streams11 * url:http://www.studytrails.com/java/java8/java8_streams/12 * url:https://www.cnblogs.com/andywithu/p/7404101.html13 */14 public class StreamDemo {15 @Test16 public void test() {17 Listgenre = new ArrayList (Arrays.asList("rock", "pop", "jazz", "reggae"));18 long a = genre.stream().filter(s -> s.startsWith("r")).count();19 System.out.println(a);20 21 boolean b = genre.stream().allMatch(s -> !s.isEmpty());22 System.out.println(b);23 24 boolean b2 = genre.stream().anyMatch(s -> s.indexOf("r") == 0);25 System.out.println(b2);26 27 System.out.println(genre.stream().peek(s -> System.out.println(s)).anyMatch(s -> s.indexOf("r") == 0));28 System.out.println(genre.stream().peek(s -> System.out.println(s)).count());29 30 }31 32 // 现在有一个List 的集合,如何把这个list转换成Map 其中,key是user id,value是User对象33 @Test34 public void test1() {35 List users = Arrays.asList(new User(1, "Tomcat"), new User(2, "Apache"), new User(3, "Nginx"));36 Map map = users.stream().collect(Collectors.toMap(obj -> obj.getId(), obj -> obj));37 System.out.println(map);38 39 // 或者使用方法的引用40 Map map2 = users.stream().collect(Collectors.toMap(User::getId, obj -> obj));41 System.out.println(map2);42 }43 44 // 把list中的每个map中的id取出来,转换成list 45 @Test46 public void test2() {47 List
User.Class
1 package org.study2.java8.stream; 2 3 4 public class User { 5 6 private int id; 7 private String name; 8 9 public User(int id, String name) {10 this.id = id;11 this.name = name;12 }13 14 public int getId() {15 return id;16 }17 18 public String toString() {19 return "User [id=" + id + ", name=" + name + "]";20 }21 22 }
详细讲解参考: