日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Stream流的收集操作

發布時間:2024/4/13 编程问答 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Stream流的收集操作 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
  • 概念

    對數據使用Stream流的方式操作完畢后,可以把流中的數據收集到集合中。

  • 常用方法

    方法名說明
    R collect(Collector collector)把結果收集到集合中
  • 工具類Collectors提供了具體的收集方式

    方法名說明
    public static <T> Collector toList()把元素收集到List集合中
    public static <T> Collector toSet()把元素收集到Set集合中
    public static Collector toMap(Function keyMapper,Function valueMapper)把元素收集到Map集合中
  • 代碼演示

public class CollectDemo {public static void main(String[] args) {//創建List集合對象List<String> list = new ArrayList<String>();list.add("林青霞");list.add("張曼玉");list.add("王祖賢");list.add("柳巖");/*//需求1:得到名字為3個字的流Stream<String> listStream = list.stream().filter(s -> s.length() == 3);//需求2:把使用Stream流操作完畢的數據收集到List集合中并遍歷List<String> names = listStream.collect(Collectors.toList());for(String name : names) {System.out.println(name);}*///創建Set集合對象Set<Integer> set = new HashSet<Integer>();set.add(10);set.add(20);set.add(30);set.add(33);set.add(35);/*//需求3:得到年齡大于25的流Stream<Integer> setStream = set.stream().filter(age -> age > 25);//需求4:把使用Stream流操作完畢的數據收集到Set集合中并遍歷Set<Integer> ages = setStream.collect(Collectors.toSet());for(Integer age : ages) {System.out.println(age);}*///定義一個字符串數組,每一個字符串數據由姓名數據和年齡數據組合而成String[] strArray = {"林青霞,30", "張曼玉,35", "王祖賢,33", "柳巖,25"};//需求5:得到字符串中年齡數據大于28的流Stream<String> arrayStream = Stream.of(strArray).filter(s -> Integer.parseInt(s.split(",")[1]) > 28);//需求6:把使用Stream流操作完畢的數據收集到Map集合中并遍歷,字符串中的姓名作鍵,年齡作值Map<String, Integer> map = arrayStream.collect(Collectors.toMap(s -> s.split(",")[0], s -> Integer.parseInt(s.split(",")[1])));Set<String> keySet = map.keySet();for (String key : keySet) {Integer value = map.get(key);System.out.println(key + "," + value);}} }

?

總結

以上是生活随笔為你收集整理的Stream流的收集操作的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。