java基础前沿--Stream流3 Stream流的收集操作

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 list = new ArrayList();
        list.add("徐晃");
        list.add("张郃");
        list.add("甘宁");
        list.add("司马懿");

        Stream listStream = list.stream().filter(s -> s.length() == 2);

        List names = listStream.collect(Collectors.toList());
        for (String name : names) {
            System.out.println(name);
        }

        String[] strArray = {"徐晃:五子良将","黄忠:五虎上将","周瑜:四都督","吕蒙:四都督","乐进:五子良将","马超:五虎上将"};

        Stream arrayStream = Stream.of(strArray).filter(s -> Integer.parseInt(String.valueOf(s.split(":")[1].length()))>3);

        Map map = arrayStream.collect(Collectors.toMap(s -> s.split(":")[0], s -> String.valueOf(s.split(":")[1])));


        Set keySet = map.keySet();
        for (String s : keySet) {
            String value = map.get(s);
            System.out.println(s+","+value);
        }
    }
}

你可能感兴趣的:(java基础前沿--Stream流3 Stream流的收集操作)