日常开发中,项目中存在大量的如下的代码:
对了,先介绍一下lambda表达式
private void testLambda() { List list = new ArrayList(); //循环此list for (int i = 0; i < list.size(); i++) { System.out.println("for循环"); } for (Object o : list) { System.out.println("forEach循环"); } //这里我们的lambda登场了 list.forEach(s -> { System.out.println("lambda表达式循环"); });}
ok,lambda表达式如上:
接着看我们的正题:如下代码
Stream entityStream = demoEntityList.stream();//获取一个并行的流文件Stream deParallel = demoEntityList.parallelStream();//lambda表达式,做简单的for循环demoEntityList.forEach(demoEntity -> System.out.println("lambda表达式"));
/** * *******场景一:******* * 根据某Id,获取实体对象列表 * 原解法: */List resultById = new ArrayList();for (DemoEntity d : demoEntityList) { if ("id".equals(d.getId())) { resultById.add(d); }}
是不是看起来很,,,烦躁,代码多了,看了起来更晕,ok
改进如下:
//改进:
demoEntityList.parallelStream().filter(demoEntity -> "id".equals(demoEntity.getId())).collect(Collectors.toList());
如此,一行代码搞定。
/** * *******场景二:******* * 根据某Id,获取对象列表内的某个元素列表 * 原解法: */List resultByIdStr = new ArrayList();for (DemoEntity d : demoEntityList) { if ("id".equals(d.getId())) { resultByIdStr.add(d.getDeName()); }}//改进:demoEntityList.parallelStream().filter(demoEntity -> "id".equals(demoEntity.getId())).map(DemoEntity::getDeName).collect(Collectors.toList());
场景还没有完,再看以下
/** * *******场景三:******* * 多条件查询取值,根据某id,获取实体对象列表,的deName值,并且deName=‘t’的对象集合 * 原解法: */List resultByIdStrName = new ArrayList();for (DemoEntity d : demoEntityList) { if ("id".equals(d.getId())) { if ("t".equals(d.getDeName())) { resultByIdStrName.add(d); } }}//改进:demoEntityList.parallelStream().filter(demoEntity -> "id".equals(demoEntity.getId())).filter(demoEntity -> "t".equals(demoEntity.getDeName())).collect(Collectors.toList());/** * *******场景四:******* * 删除集合内,某个字段值 * 原解法: */for (DemoEntity d : demoEntityList) { if ("id".equals(d.getId())) { d.setDeAge(null); d.setDeName(null); }}//改进:demoEntityList.parallelStream().peek(demoEntity -> { demoEntity.setDeName(null); demoEntity.setDeAge(null);}).collect(Collectors.toList());/** * 改进场景:更换id为“1”的名称为“t” */demoEntityList.parallelStream().peek(demoEntity -> { if ("1".equals(demoEntity.getId())) { demoEntity.setDeName("t"); }}).collect(Collectors.toList());
看着改进场景,这样写,代码是不是看起来,清清爽爽一目了然。
这里产生了一个严重问题:
之前我们的for循环,是一条条执行循环内的数据
stream.parallel.forEach()被我们程为流,多线程,并非安全线程,
一定注意…循环更新删除,数据谨记加锁操作。。
over,改进写法完成
作者:木子啦啦啦啦
原文链接:https://blog.csdn.net/qq_42685333/article/details/103929287