当前位置: 代码迷 >> 综合 >> Java8 Stream 之filter 用法
  详细解决方案

Java8 Stream 之filter 用法

热度:79   发布时间:2023-12-18 12:47:44.0
filter 的作用是接受lamda ,排除某些元素。简单理解就是过滤器。
stream 的用法,分为几个步骤。
1.中间操作 主要是创建stream 对象,对需要过滤的集合对象 使用stream().filter(lamda)
2.终止操作 stream 对象进行输出需求:找到product 等于apple的这条键值对的数据。
{password=123456, product=apple, username=test.cn.01}
{password=123456, product=huawei, username=test.cn.01}
{password=123456, product=samsung, username=test.cn.01}@Test
public void testFilter(){List<HashMap<String,String>> maps =new ArrayList<HashMap<String, String>>();HashMap<String,String> hashMap =new HashMap<>();for (int i = 0; i < 3; i++) {String product = i==0?"apple":i==2?"huawei":"samsung";hashMap.put("username","test.cn.01");hashMap.put("password","123456");hashMap.put("product",product);maps.add(hashMap);hashMap =new HashMap<>();}Stream<HashMap<String, String>> stream = maps.stream().filter((map) -> map.get("product") == "apple");stream.forEach(System.out::println);}

 

Output:
[TestNG] Running:
 {password=123456, product=apple, username=test.cn.01}

 

  相关解决方案