toList():把元素收集到List集合中
toSet():把元素收集到Set集合中
toMap(Function keyMapper,Function valueMapper):把元素收集到到Map集合中
import java.awt.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class test {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("徐晃");
list.add("张郃");
list.add("甘宁");
list.add("司马懿");
Stream<String> listStream = list.stream().filter(s -> s.length() == 2);
List<String> names = listStream.collect(Collectors.toList());
for (String name : names) {
System.out.println(name);
}
String[] strArray = {"徐晃:五子良将","黄忠:五虎上将","周瑜:四都督","吕蒙:四都督","乐进:五子良将","马超:五虎上将"};
Stream<String> arrayStream = Stream.of(strArray).filter(s -> Integer.parseInt(String.valueOf(s.split(":")[1].length()))>3);
Map<String,String> map = arrayStream.collect(Collectors.toMap(s -> s.split(":")[0], s -> String.valueOf(s.split(":")[1])));
Set<String> keySet = map.keySet();
for (String s : keySet) {
String value = map.get(s);
System.out.println(s+","+value);
}
}
}