java8利用Stream方法求两个List对象的交集、差集与并集(即:anyMatch和allMatch和noneMatch的区别详解)

本文主要是介绍java8利用Stream方法求两个List对象的交集、差集与并集(即:anyMatch和allMatch和noneMatch的区别详解),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1、anyMatch 
判断数据列表中是否存在任意一个元素符合设置的predicate条件,如果是就返回true,否则返回false。

接口定义:
boolean anyMatch(Predicate<? super T> predicate);

方法描述:
在anyMatch 接口定义中是接收 Predicate 类型参数,在Lamdba表达式中 Predicate<T> 是接收一个T类型参数,然后经过逻辑验证返回布尔值结果。这里anyMatch表示,判断的条件里,任意一个元素符合条件,就返回true值。

使用场景:

两个集合的交集
 

    @Testpublic void a17() {List<User> list = new ArrayList<>();list.add(new User("张三", 12, "南京"));list.add(new User("李四", 13, "北京"));list.add(new User("王五", 14, "苏州"));list.add(new User("王五", 17, "苏州"));List<User> userList = new ArrayList<>();userList.add(new User("李四", 13, "北京"));userList.add(new User("王五", 20, "广州"));// 获取两个集合中有相同名字或者年龄相同的,只要满足其中一个条件即可,只会返回list集合里面的元素,有先后顺序返回List<User> users1 = list.stream().filter(a -> userList.stream().anyMatch(b -> a.getName().equals(b.getName()) || a.getAge() == b.getAge())).collect(Collectors.toList());// 获取两个集合中相同名字并且年龄相同的,必须同时满足两个条件List<User> users2 = list.stream().filter(a -> userList.stream().anyMatch(b -> a.getName().equals(b.getName()) && a.getAge() == b.getAge())).collect(Collectors.toList());users1.forEach(item -> {System.out.println(item.getName() + item.getAge() + item.getEmailAddress());});/** 第一种结果展示:* 李四13北京* 王五14苏州* 王五17苏州*/users2.forEach(item -> {System.out.println(item.getName() + item.getAge() + item.getEmailAddress());});/** 第二种结果展示:* 李四13北京*/}@Test
public void a15() {Stream<String> stream = Stream.of("ac", "bcddddd", "bd");// 判断stream中其中任何一个元素中只要有包含b字符串或者l字符串就返回trueboolean isMatch = stream.anyMatch(str -> str.contains("b") || str.contains("l"));System.out.println(isMatch);  // true
}

2、allMatch
判断数据列表中全部元素都符合设置的predicate条件,如果是就返回true,否则返回false,流为空时总是返回true。

接口定义:
boolean allMatch(Predicate<? super T> predicate);

方法描述:
在allMatch 接口定义中是接收 Predicate 类型参数,在Lamdba表达式中 Predicate<T> 是接收一个T类型参数,然后经过逻辑验证返回布尔值结果。这里allMatch表示,判断的条件里,全部元素符合条件,就返回true值。

适用场景:

基本类型的集合,但不适合于对象集合(我自己的理解)

allMatch里面不适合写 && ,只适合写 ||,如果写&&,编译器会自动报黄色波浪线
 

@Test
public void a18() {List<String> typeList1 = Arrays.asList("1", "2");List<String> typeList2 = Arrays.asList("1", "2", "3", "4");// 集合列表中全部元素必须在allMatch里面的那些字符串,只要全部元素中有任意一个不同的元素在AllMatch中就返回falseboolean isMatch1 = typeList1.stream().allMatch(a -> a.equals("1") || a.equals("2") || a.equals("3"));boolean isMatch2 = typeList2.stream().allMatch(a -> a.equals("1") || a.equals("2") || a.equals("3"));System.out.println(isMatch1);   // trueSystem.out.println(isMatch2);   // false
}@Test
public void a16() {Stream<String> stream = Stream.of("abc", "abc", "bcd");// 判断stream中全部所有元素必须全部包含b字符串和c字符串就返回true,如果有一个元素不包含这两个字符串就返回falseboolean isMatch = stream.allMatch(str -> str.contains("b") && str.contains("c"));System.out.println(isMatch);  // true
}

3、noneMatch
判断数据列表中全部元素都不符合设置的predicate条件,如果是就返回true,否则返回false,流为空时总是返回true。

接口定义:
boolean noneMatch(Predicate<? super T> predicate);

方法描述:
在noneMatch接口定义中是接收 Predicate 类型参数,在Lamdba表达式中 Predicate<T> 是接收一个T类型参数,然后经过逻辑验证返回布尔值结果。这里noneMatch表示与allMatch相反,判断的条件里的元素,所有的元素都不符合,就返回true值。

适用场景:

两个集合的差集 (本人只想到这么做,如果有更简洁的可以告诉我怎么写,感谢0.0)
 

@Test
public void a17() {List<User> list = new ArrayList<>();list.add(new User("张三", 12, "南京"));list.add(new User("李四", 13, "北京"));list.add(new User("王五", 14, "苏州"));list.add(new User("王五", 17, "苏州"));List<User> userList = new ArrayList<>();userList.add(new User("李四", 13, "北京"));userList.add(new User("王五", 20, "广州"));// 获取list集合和userList集合过滤掉两者集合中名字和年龄相同的数据后,只返回list集合的数据List<User> users3 = list.stream().filter(a -> userList.stream().noneMatch(b -> a.getName().equals(b.getName()) && a.getAge() == b.getAge())).collect(Collectors.toList());// 获取userlist集合和list集合过滤掉两者集合中名字和年龄相同的数据后,只返回userList集合的数据List<User> users4 = userList.stream().filter(a -> list.stream().noneMatch(b -> a.getName().equals(b.getName()) && a.getAge()==b.getAge())).collect(Collectors.toList());// 获取list和userList集合之间的差集,将上面两者集合合并,就是两个集合的差集List<User> arrayList = new ArrayList<>();arrayList.addAll(users3);arrayList.addAll(users4);arrayList.forEach(item -> {System.out.println(item.getName() + item.getAge() + item.getEmailAddress());});/**  两者集合之间的差集* 张三12南京* 王五14苏州* 王五17苏州* 王五20广州*/System.out.println("-------------------");users3.forEach(item -> {System.out.println(item.getName() + item.getAge() + item.getEmailAddress());});/**  只返回list集合中过滤掉之后的元素集合* 张三12南京* 王五14苏州* 王五17苏州*/System.out.println("-------------------");users4.forEach(item -> {System.out.println(item.getName() + item.getAge() + item.getEmailAddress());});/**  只返回userList集合中过滤掉之后的元素集合* 王五20广州*/
}@Test
public void a19() {List<String> typeList1 = Arrays.asList("1", "2");List<String> typeList2 = Arrays.asList("1", "2", "3", "4");// 集合列表中全部元素只要都不在noneMatch里面的判断中,就返回true,集合列表中任何元素中只要有一个在noneMatch的判断中就返回falseboolean isMatch1 = typeList1.stream().noneMatch(a -> a.equals("3") || a.equals("4"));boolean isMatch2 = typeList2.stream().noneMatch(a -> a.equals("1") || a.equals("2") || a.equals("3"));System.out.println(isMatch1);   // trueSystem.out.println(isMatch2);   // false
}/** noneMatch */
@Test
public void a20() {Stream<String> stream = Stream.of("dddd", "ee", "qqq", "bcfff");// 判断 stream 中所有的元素都不是以 a 开头,就返回true,如果所有的元素中只要其中一个元素是以a开头的,就返回falseboolean isMatch = stream.noneMatch(str->str.startsWith("a"));System.out.println(isMatch);  // true
}

这篇关于java8利用Stream方法求两个List对象的交集、差集与并集(即:anyMatch和allMatch和noneMatch的区别详解)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/329096

相关文章

JVM 的类初始化机制

前言 当你在 Java 程序中new对象时,有没有考虑过 JVM 是如何把静态的字节码(byte code)转化为运行时对象的呢,这个问题看似简单,但清楚的同学相信也不会太多,这篇文章首先介绍 JVM 类初始化的机制,然后给出几个易出错的实例来分析,帮助大家更好理解这个知识点。 JVM 将字节码转化为运行时对象分为三个阶段,分别是:loading 、Linking、initialization

Spring Security 基于表达式的权限控制

前言 spring security 3.0已经可以使用spring el表达式来控制授权,允许在表达式中使用复杂的布尔逻辑来控制访问的权限。 常见的表达式 Spring Security可用表达式对象的基类是SecurityExpressionRoot。 表达式描述hasRole([role])用户拥有制定的角色时返回true (Spring security默认会带有ROLE_前缀),去

浅析Spring Security认证过程

类图 为了方便理解Spring Security认证流程,特意画了如下的类图,包含相关的核心认证类 概述 核心验证器 AuthenticationManager 该对象提供了认证方法的入口,接收一个Authentiaton对象作为参数; public interface AuthenticationManager {Authentication authenticate(Authenti

Spring Security--Architecture Overview

1 核心组件 这一节主要介绍一些在Spring Security中常见且核心的Java类,它们之间的依赖,构建起了整个框架。想要理解整个架构,最起码得对这些类眼熟。 1.1 SecurityContextHolder SecurityContextHolder用于存储安全上下文(security context)的信息。当前操作的用户是谁,该用户是否已经被认证,他拥有哪些角色权限…这些都被保

Spring Security基于数据库验证流程详解

Spring Security 校验流程图 相关解释说明(认真看哦) AbstractAuthenticationProcessingFilter 抽象类 /*** 调用 #requiresAuthentication(HttpServletRequest, HttpServletResponse) 决定是否需要进行验证操作。* 如果需要验证,则会调用 #attemptAuthentica

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

Java架构师知识体认识

源码分析 常用设计模式 Proxy代理模式Factory工厂模式Singleton单例模式Delegate委派模式Strategy策略模式Prototype原型模式Template模板模式 Spring5 beans 接口实例化代理Bean操作 Context Ioc容器设计原理及高级特性Aop设计原理Factorybean与Beanfactory Transaction 声明式事物

Java进阶13讲__第12讲_1/2

多线程、线程池 1.  线程概念 1.1  什么是线程 1.2  线程的好处 2.   创建线程的三种方式 注意事项 2.1  继承Thread类 2.1.1 认识  2.1.2  编码实现  package cn.hdc.oop10.Thread;import org.slf4j.Logger;import org.slf4j.LoggerFactory

OpenHarmony鸿蒙开发( Beta5.0)无感配网详解

1、简介 无感配网是指在设备联网过程中无需输入热点相关账号信息,即可快速实现设备配网,是一种兼顾高效性、可靠性和安全性的配网方式。 2、配网原理 2.1 通信原理 手机和智能设备之间的信息传递,利用特有的NAN协议实现。利用手机和智能设备之间的WiFi 感知订阅、发布能力,实现了数字管家应用和设备之间的发现。在完成设备间的认证和响应后,即可发送相关配网数据。同时还支持与常规Sof

JAVA智听未来一站式有声阅读平台听书系统小程序源码

智听未来,一站式有声阅读平台听书系统 🌟&nbsp;开篇:遇见未来,从“智听”开始 在这个快节奏的时代,你是否渴望在忙碌的间隙,找到一片属于自己的宁静角落?是否梦想着能随时随地,沉浸在知识的海洋,或是故事的奇幻世界里?今天,就让我带你一起探索“智听未来”——这一站式有声阅读平台听书系统,它正悄悄改变着我们的阅读方式,让未来触手可及! 📚&nbsp;第一站:海量资源,应有尽有 走进“智听