java項目中流式表達式的使用

流式表達式流式表達式是jdk8帶來的java的新特性詳情: https://www.cnblogs.com/aiqiqi/p/11004208.htmlhttps://blog.csdn.net/weixin_37948888/article/details/96995312
在這裏插入圖片描述

流式表達式的常見使用的場景

//1列出班上超過85分的學生姓名,並按照分數降序輸出用戶名字@Test
public void test1() {
    List<String> studentList = stuList.stream()
            .filter(x->x.getScore()>85)
            .sorted(Comparator.comparing(Student::getScore).reversed())
            .map(Student::getName)
            .collect(Collectors.toList());
    System.out.println(studentList);
}

創建流的方式
* 通過數組創建
* 通過集合創建
* 創建空的流
* 創建無限流(通過limit可以實現限制大小)
* 創建規律的無限流

普通流和並行流
並行流 就是把一個內容分成多個數據塊,並用不同的線程分別處理每個數據塊的流(其背後是Fork/Join框架)
Stream API可以聲明性地通過parallel()與sequential()在並行流與順序流之間進行切換。

List<String> strs = Arrays.asList("11212","dfd","2323","dfhgf");
//創建普通流
Stream<String> stream  = strs.stream();
//創建並行流(即多個線程處理)
Stream<String> stream1 = strs.parallelStream();

在項目中經常使用的場景

//解決key值一對多的問題
Map<String, String> mmapCodeDeptName = mapAllDeptNameCode.stream().collect(Collectors.toMap( AllDeptNameCodePojo::getDeptCode,AllDeptNameCodePojo::getDeptName,(k,v)->v));

//解決 value可能爲空的情況
Map<String, String> mmapCodeParentId = mapAllDeptNameCode.stream().collect(Collector.of(HashMap::new, (m, per)->m.put(per.getDeptCode(),per.getParentId()), (k, v)->v, Collector.Characteristics.IDENTITY_FINISH));

//截取(場景:分批次處理集合 相當於 List.subList())
add.stream().skip(i * 1000).limit(1000).collect(Collectors.toList())
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章