Stream語法詳解
Stream當成一個高級版本的Iterator。原始版本的Iterator,用戶只能一個一個的遍歷元素並對其執行某些操作;高級版本的Stream,用戶只要給出需要對其包含的元素執行什么操作,比如“過濾掉長度大於10的字符串”、“獲取每個字符串的首字母”等,具體這些操作如何應用到每個元素上,就給Stream就好了
- 創建Stream;
- 轉換Stream,每次轉換原有Stream對象不改變,返回一個新的Stream對象(**可以有多次轉換**);
- 對Stream進行聚合(Reduce)操作,獲取想要的結果
一、List中去除重復的String
public List<String> removeStringListDupli(List<String> stringList) { Set<String> set = new LinkedHashSet<>(); set.addAll(stringList); stringList.clear(); stringList.addAll(set); return stringList; }
二、List中依據對象屬性去重
List<Person> unique = persons.stream().collect( collectingAndThen( toCollection(() -> new TreeSet<>(comparingLong(Person::getId))), ArrayList::new) );