我的知识梳理-stream

jdk8引入了lambda表达式和stream,用起来还是很舒服的,记录一下常见的几种用法

1、forEach 

public class ForEachMain {
    public static void main(String[] args) {
        //简单的打印,两段代码的功能相同
        new ArrayList<>().forEach(System.out::println);
        new ArrayList<>().forEach(i-> System.out.println(i));
        new HashMap<>().forEach((k,v)-> {
            System.out.println(k);
            System.out.println(v);
        });
        //下面两段代码功能相同
        IntStream.range(0,10000).forEach(i-> System.out.println(i));
        for (int i = 0; i < 10000; i++) {
            System.out.println(i);
        }
    }
}

2、map 

将流中的所有对象,根据一个函数转换成另外一种对象

public class MapMain {
    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();
        List<Integer> intList = stringList.stream().map(Integer::valueOf).collect(Collectors.toList());
    }

}

3、groupBy

将流中的所有对象,按照一个函数获取key分组形成一个map

public class GroupByMain {
    public static void main(String[] args) {
        List<A> aList = new ArrayList<>();
        aList.add(new A("1", "first"));
        aList.add(new A("2", "second"));
        aList.add(new A("1", "third"));

        Map<String, List<A>> aMap = aList.stream().collect(Collectors.groupingBy(A::getVersion));
        System.out.println(aMap);
    }
}

//{1=[{"version":"1","name":"first"}, {"version":"1","name":"third"}], 2=[{"version":"2","name":"second"}]}

4、map

将流中的所有元素,根据一个函数得到key,再根据一个函数得到value,形成一个map

public static void main(String[] args) {
        List<Thread> threads = new ArrayList<>();
        threads.add(new Thread("thread1"));
        threads.add(new Thread("thread2"));
        threads.add(new Thread("thread3"));

        //线程名-线程对象的map
        Map<String, Thread> threadMap = threads.stream().collect(Collectors.toMap(Thread::getName, Function.identity()));
        //线程名-线程对象的map另一种写法
        Map<String, Thread> threadMap1 = threads.stream().collect(Collectors.toMap(Thread::getName, i -> i));
        //线程名-线程id的map
        Map<String, Long> threaNameAndIdMap = threads.stream().collect(Collectors.toMap(Thread::getName, Thread::getId));
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值