stream排序、筛选、截取、统计、多字段去重等操作

时间:2025-03-19 10:51:37

简单举例介绍比较方便不复杂的Stream流方法,提升编程效率

public class StreamTest {
	
	public static void main(String[] args) {
		List<TestData>mlist = new ArrayList<TestData>();
		
		TestData data;
		//字段名为name,time,age
		data = new TestData("大毛", "2020-01-01",21);
		(data);
		data = new TestData("二毛", "2020-02-08",12);
		(data);
		data = new TestData("三毛", "",23);
		(data);
		data = new TestData("四毛", "2020-03-03",17);
		(data);
		List<TestData> squaresList = ()
		//下面是筛选
        .filter(o -> !().contains("08"))
        .filter(o -> !().isEmpty())
        //下面是排序
        .sorted((TestData::getTime).reversed())
        .sorted((o1,o2) -> ()-())
        //下面这一行把list列表数据返回,不写就是一个布尔类型结果返回
        .collect(())
        //下面是截取,只取结果种的前两条数据
        .subList(0,2);
	}
}
//提取list集合中的对象某个字段然后生成对应的新集合
List<Integer> modelItemIds = ().getAssessmentItems().stream().map(AssessmentItemPo::getModelItemId).collect(());
字段累加求和
int total = ().mapToInt(CaseInfoVO::getPersonValue).sum();

concat:将格式相同的两个stream合并在一起
skip:跳过

(().filter(s -> () == 3).limit(3),
                ().filter(s -> ("林")).skip(1)).map(Actor::new).
                forEach(p -> (()));

筛选集合中某字段不为null或者“”的集合

 List<String> filterContentList = ().map(LegalVo::getContent).filter(StrUtil::isNotBlank).collect(());

对List(Map)进行

//方法一
().sorted(((Map<String, Object> h) -> ((String) ("dateTime")))).collect(());
//方法二----添加静态方法
private static Integer sortMap(Map<String,Object> map){
    return (("evtId").toString());
}
//比较方法中添加类名(SendServiceImpl)::静态方法(sortMap)即可
List<Map<String,Object>> newMapList = ().sorted((SendServiceImpl::sortMap)).collect(());;

多字段去重

        //去重
        ArrayList<Map<String, Object>> collect = ().collect(((() ->
                new TreeSet<>((o -> ("currentDepartName") + ";"
                        + ("currentUserName") + ";" + ("handleType") + ";"
                        + ("nextDepartName")))), ArrayList::new));