生活随笔
收集整理的這篇文章主要介紹了
Stream流的收集操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
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流的收集操作的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。