用Stream流遍历两个集合,对比出数据差异。

您所在的位置:网站首页 list过滤filter 用Stream流遍历两个集合,对比出数据差异。

用Stream流遍历两个集合,对比出数据差异。

2023-06-10 10:01| 来源: 网络整理| 查看: 265

今天开发一个需求时,要对A和B两个List集合遍历,并比较出集合A有,而集合B没有的值。 比如说List集合A有’one’,‘two’,‘three’三个值,List集合B有’one’,‘three’两个值。 那么最终打印’two’。 下面我就用stream流来做个例子。 例子中,集合A的泛型为HashMap,集合B的泛型为String。

Stream流中,forEach()方法用于对一个流进行结尾动作,同时对最终过滤后的元素结果进行一个遍历操作。 我们可以在forEach()中直接写入类和其对应方法名,来对过滤后的元素进行操作。如以下的示例中的forEach(System.out::println)

@org.junit.Test public void streamList(){ HashMap hashMapOne = new HashMap(); hashMapOne.put("userid","one" ); HashMap hashMapTwo = new HashMap(); hashMapTwo.put("userid","two" ); HashMap hashMapThree = new HashMap(); hashMapThree.put("userid","three" ); List listMap = new ArrayList(); listMap.add(hashMapOne); listMap.add(hashMapTwo); listMap.add(hashMapThree); List elementList = new ArrayList(); elementList.add("one"); //elementList.add("two"); elementList.add("three"); //通过filter方法,过滤每个元素。你需要在filter方法内通过lambda表达式,来定义对每个元素的过滤流程。 listMap.stream().filter( itemmap -> { int hit = 0;//是否命中; 0:未命中 >0:命中 for (int i = 0; i hit++; } }; return hit == 0 ? true:false;//如果返回值为true,则将该元素交给下一个Stream流环节,也就是交给forEach方法来处理。 }).forEach(System.out::println);//通过filter方法过滤后的元素,再通过forEach方法对每个元素进行使用。 // 我们可以在forEach方法内,使用System.out.println来对过滤后的元素打印。 }

在这里插入图片描述

同样的,forEach()方法也可以如同filter()方法那样,在方法里头通过lambda表达式,来对元素进行更为细致的操作。如以下示例中的

forEach( filterResultItem -> { filterResult.add(filterResultItem.get(“userid”)); });

@org.junit.Test public void streamList(){ HashMap hashMapOne = new HashMap(); hashMapOne.put("userid","one" ); HashMap hashMapTwo = new HashMap(); hashMapTwo.put("userid","two" ); HashMap hashMapThree = new HashMap(); hashMapThree.put("userid","three" ); List listMap = new ArrayList(); listMap.add(hashMapOne); listMap.add(hashMapTwo); listMap.add(hashMapThree); List elementList = new ArrayList(); elementList.add("one"); //elementList.add("two"); elementList.add("three"); ArrayList filterResult = new ArrayList(); //通过filter方法,过滤每个元素。你需要在filter方法内通过lambda表达式,来定义对每个元素的过滤流程。 listMap.stream().filter( itemmap -> { int hit = 0;//是否命中; 0:未命中 >0:命中 for (int i = 0; i hit++; } }; return hit == 0 ? true:false;//如果返回值为true,则将该元素交给下一个Stream流环节,也就是交给forEach方法来处理。 }).forEach( filterResultItem -> { filterResult.add(filterResultItem.get("userid")); });//通过filter方法过滤后的元素,再通过forEach方法对每个元素进行使用。 // 不仅仅是类似于System.out::println这样的形式来指定类和其对应的方法名对过滤后的元素进行操作。 // 我们也可以在forEach方法内,以lambda表达式的方式,来对过滤后的元素进行更为细致的操作。 System.out.println(filterResult); }

在这里插入图片描述



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3