Java Stream

Posted in :

什麼是Stream

Stream是一種處理集合(Collection)資料的方式。 Stream可以讓我們以更簡潔的方式對集合進行過濾(filter)、映射(map)、排序(sort)等操作。

Stream是Java 8 API新增的一個新的抽象,以一種聲明性方式處理資料集合(專注於來源資料運算能力的封裝,並且支援序列與並行兩種操作方式)。

Stream是從支援資料處理操作的來源產生的元素序列,來源可以是陣列、檔案、集合、函數。

Stream是對集合(Collection)物件功能的增強,與Lambda表達式結合,可提高程式效率、間接性和程式可讀性。

使用範例

範例1號: 取得1維陣列集合

ArrayList list = new ArrayList<>();
Collections.addAll(list, "a", "b", "c", "d", "e", "f");
Stream stream = list.stream();
stream.forEach(s -> System.out.println(s));

範例2號: Array 轉 stream

int[] arr = {1, 2, 3, 4, 5, 6, 7, 8, 9};
Arrays.stream(arr).forEach(s-> System.out.println(s));

範例3號: 取得字典或對映集合

HashMap hm = new HashMap<>();
hm.put("aaa", 111);
hm.put("bbb", 222);
hm.put("ccc", 333);
hm.put("ddd", 444);
// key 值集合
hm.keySet().stream().forEach(s -> System.out.println(s));
// 對映值集合
hm.entrySet().stream().forEach(s -> System.out.println(s));

範例4號: 遍歷/加總/轉成陣列

ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "A", "B", "C");
 
// 遍歷
list.stream().forEach(s -> System.out.println(s));
 
// 加總
long count = list.stream().count();
System.out.println(count);
 
// stream() 轉成陣列
Object[] obj = list.stream().toArray();
System.out.println(Arrays.toString(obj));

範例5號: 內容過濾

ArrayList<String> list = new ArrayList<>();
Collections.addAll(list, "男-32", "女-18", "女-19", "男-26");
 
 
// 收集男性, 轉成List集合
List<String> collect = list.stream().filter(s -> "男".equals(s.split("-")[0])).collect(Collectors.toList());
System.out.println(collect);
 
 
// 收集男性, 轉成Set集合, 
Set<String> collect1 = list.stream().filter(s -> "男".equals(s.split("-")[1])).collect(Collectors.toSet());
System.out.println(collect1);

範例6號: 檢查2 Set 是否為子集合

Set<Integer> a_set= new HashSet<>();
a_set.add(1);
a_set.add(2);

Set<Integer> b_set= new HashSet<>();
b_set.add(2);

Set<Object> intersection = a_set.stream()
    .distinct()
    .filter(b_set::contains)
    .collect(Collectors.toSet());
System.out.println("subset:"+ !intersection.isEmpty());

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *