package lambda.list;
import cn.hutool.core.util.ObjectUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;
import pojo.Dome;
import java.util.ArrayList;
import java.util.List;
/**
* @Author: xxx
* @date 2021/5/14
**/
@Slf4j
public class SearchTest {
/***
* 初始化测试数组
* @date 2021/5/14
**/
private List<Dome> initArray() {
Dome dome1 = new Dome("张三", 11.0, 10);
Dome dome2 = new Dome("李四", 61.0, 11);
Dome dome3 = new Dome("王五", 26.0, 12);
Dome dome4 = new Dome("张三", 14.0, 14);
Dome dome5 = new Dome("王五", 24.0, 15);
Dome dome6 = new Dome("李四", 16.0, 16);
Dome dome7 = new Dome("赵六", 35.0, 17);
List<Dome> domes = new ArrayList<>();
domes.add(dome1);
domes.add(dome2);
domes.add(dome3);
domes.add(dome4);
domes.add(dome5);
domes.add(dome6);
domes.add(dome7);
log.info("domes : {}", domes);
return domes;
}
/***
* List 查找
* @date 2021/5/13
**/
@Test
public void searchTest1() {
List<Dome> domes = initArray();
/*
1.Matching
Stream提供了anyMatch(), allMatch(), noneMatch()这三种match方式
anyMatch(Predicate p) 传入一个断言型函数,对流中所有的元素进行判断,
只要有一个满足条件就返回true,都不满足返回false。
*/
boolean b = domes.stream().anyMatch(vo -> ObjectUtil.isNotNull(vo.getName()) && "赵六".equals(vo.getName()));
log.info("b : {}", b);
/*
domes : [Dome{name='张三', money=11.0, age=10}, Dome{name='李四', money=61.0, age=11}, Dome{name='王五', money=26.0, age=12}, Dome{name='张三', money=14.0, age=14}, Dome{name='王五', money=24.0, age=15}, Dome{name='李四', money=16.0, age=16}, Dome{name='赵六', money=35.0, age=17}]
b : true
*/
}
/**
* 判断集合中的元素是否满足条件
*/
@Test
public void searchTest2(){
List<Dome> domes = initArray();
//并行流parallelStream
domes.parallelStream().forEach(element -> System.out.println("element = " + element));
// 打印线程 -Djava.util.concurrent.ForkJoinPool.common.parallelism=N 虚拟机启动参数来设置worker(N)的数量
domes.parallelStream().forEach(element -> System.out.println(Thread.currentThread().getName() + " >>> " + element));
//只要有一个条件满足即返回true
boolean isValid = domes.stream().anyMatch(element -> element.getName().contains("张三"));
System.out.println("isValid = " + isValid);
//必须全部都满足才会返回true
boolean isValidOne = domes.stream().allMatch(element -> element.getName().contains("张三"));
System.out.println("isValidOne = " + isValidOne);
//全都不满足才会返回true
boolean isValidTwo = domes.stream().noneMatch(element -> element.getName().contains("张三"));
System.out.println("isValidTwo = " + isValidTwo);
}
}
标签:anyMatch,domes,java,noneMatch,money,List,Dome,element,new
From: https://www.cnblogs.com/fuqian/p/17285737.html