c++ 11新特性总结_JDK1.8新特性Stream和Collectors19个常用示例总结
生活随笔
收集整理的這篇文章主要介紹了
c++ 11新特性总结_JDK1.8新特性Stream和Collectors19个常用示例总结
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
關于Stream和Collectors的用法,這應該是總結的最全的文章了,大家可以收藏一下。
一:簡介
java.util.Stream 表示能應用在一組元素上一次執行的操作序列。Stream 操作分為中間操作或者最終操作兩種,最終操作返回一特定類型的計算結果,而中間操作返回Stream本身,這樣就可以將多個操作依次串起來。Stream 的創建需要指定一個數據源,比如 java.util.Collection的子類,List或者Set, Map不支持。Stream的操作可以串行stream()執行或者并行parallelStream()執行。
二:示例
1. forEach 循環
@Testpublic void forEach(){ // 你不鳥我,我也不鳥你 List list = Arrays.asList("you", "don't", "bird", "me", ",", "I", "don't", "bird", "you"); // 方式一:JDK1.8之前的循環方式 for (String item: list) { System.out.println(item); } // 方式二:使用Stream的forEach方法 // void forEach(Consumer super T> action) list.stream().forEach(item -> System.out.println(item)); // 方式三:方式二的簡化方式 // 由于方法引用也屬于函數式接口,所以方式二Lambda表達式也可以使用方法引用來代替 // 此種方式就是方式一、方式二的簡寫形式 list.stream().forEach(System.out::println);}2. filter 過濾
public class User { private Long id; private String phone; private Integer age;public User(){} public User(Long id, String username, Integer age) { this.id = id; this.username = username; this.age = age; }// Getter & Setter & toString}@Testpublic void filter(){List users = Arrays.asList( new User(1L, "mengday", 28), new User(2L, "guoguo", 18), new User(3L, "liangliang", 17) ); // Stream filter(Predicate super T> predicate); users.stream().filter(user -> user.getAge() > 18).forEach(System.out::println);}3. map 映射
@Testpublic void map(){ List list = Arrays.asList("how", "are", "you", "how", "old", "are", "you", "?"); // Stream map(Function super T, ? extends R> mapper); list.stream().map(item -> item.toUpperCase()).forEach(System.out::println);}4. flatMap
@Testpublic void flatMap(){ List a = Arrays.asList(1, 2, 3); List b = Arrays.asList(4, 5, 6); // Stream flatMap(Function super T, ? extends Stream extends R>> mapper) List> collect = Stream.of(a, b).collect(Collectors.toList()); // [[1, 2, 3], [4, 5, 6]] System.out.println(collect); // 將多個集合中的元素合并成一個集合 List mergeList = Stream.of(a, b).flatMap(list -> list.stream()).collect(Collectors.toList()); // [1, 2, 3, 4, 5, 6] System.out.println(mergeList); // 通過Builder模式來構建 Stream stream = Stream.builder().add("hello").add("hi").add("byebye").build();}5. sorted 排序
@Testpublic void sort(){ List list = Arrays.asList("c", "e", "a", "d", "b"); // Stream sorted(Comparator super T> comparator); // int compare(T o1, T o2); list.stream().sorted((s1, s2) -> s1.compareTo(s2)).forEach(System.out::println);}6. distinct 去重復
@Testpublic void distinct(){ // 知之為知之,不知為不知 Stream stream = Stream.of("know", "is", "know", "noknow", "is", "noknow"); stream.distinct().forEach(System.out::println); // know is noknow}7. count 總數量
@Testpublic void count(){ Stream stream = Stream.of("know", "is", "know", "noknow", "is", "noknow"); long count = stream.count(); System.out.println(count);}8. min、max
@Testpublic void min(){ List list = Arrays.asList("1", "2", "3", "4", "5"); // Optional min(Comparator super T> comparator); Optional optional = list.stream().min((a, b) -> a.compareTo(b)); String value = optional.get(); System.out.println(value);}9. skip、limit
@Testpublic void skip(){ List list = Arrays.asList("a", "b", "c", "d", "e"); // Stream skip(long n) list.stream().skip(2).forEach(System.out::println); // c、d、e}@Testpublic void limit(){ List list = Arrays.asList("a", "b", "c", "d", "e"); list.stream().skip(2).limit(2).forEach(System.out::println); // c、d}10. collect
@Testpublic void collect(){ List list = Arrays.asList("a", "b", "c", "d", "e"); // Stream -> Collection List collect = list.stream().collect(Collectors.toList()); // Stream -> Object[] Object[] objects = list.stream().toArray();}11. concat
@Testpublic void concat(){ List list = Arrays.asList("a", "b"); List list2 = Arrays.asList("c", "d"); Stream concatStream = Stream.concat(list.stream(), list2.stream()); concatStream.forEach(System.out::println);}12. anyMatch、allMatch
@Testpublic void match(){ // 你給我站住 List list = Arrays.asList("you", "give", "me", "stop"); // boolean anyMatch(Predicate super T> predicate); // parallelStream可以并行計算,速度比stream更快 boolean result = list.parallelStream().anyMatch(item -> item.equals("me")); System.out.println(result);}/*** anyMatch偽代碼 * 如果集合中有一個元素滿足條件就返回true * @return */public boolean anyMatch() { List list = Arrays.asList("you", "give", "me", "stop"); for (String item : list) { if (item.equals("me")) { return true; } } return false;}13. reduce 歸納
@Testpublic void reduce(){ Stream stream = Stream.of("you", "give", "me", "stop"); // Optional reduce(BinaryOperator accumulator); Optional optional = stream.reduce((before, after) -> before + "," + after); optional.ifPresent(System.out::println); // you,give,me,stop}14. findFirst、findAny
@Testpublic void findFirst(){ Stream stream = Stream.of("you", "give", "me", "stop"); String value = stream.findFirst().get(); System.out.println(value);}@Testpublic void findAny(){ Stream stream = Stream.of("you", "give", "me", "stop"); String value2 = stream.findAny().get(); System.out.println(value2);}15. 流轉換成集合
@Testpublic void testToCollection(){ List list = Arrays.asList(1, 2, 3); // [10, 20, 30] List collect = list.stream().map(i -> i * 10).collect(Collectors.toList()); // [20, 10, 30] Set collect1 = list.stream().map(i -> i * 10).collect(Collectors.toSet()); // {key1=value:10, key2=value:20, key3=value:30} Map collect2 = list.stream().map(i -> i * 10).collect(Collectors.toMap(key -> "key" + key/10, value -> "value:" + value)); // [1, 3, 4] TreeSet collect3= Stream.of(1, 3, 4).collect(Collectors.toCollection(TreeSet::new));}@Data@ToString@AllArgsConstructor@RequiredArgsConstructorpublic class User { private Long id; private String username;}@Testpublic void testToMap() {List userList = Arrays.asList( new User(1L, "mengday"), new User(2L, "mengdee"), new User(3L, "mengdy"));// toMap 可用于將List轉為Map,便于通過key快速查找到某個valueMap userIdAndModelMap = userList.stream().collect(Collectors.toMap(User::getId, Function.identity()));User user = userIdAndModelMap.get(1L);// User(id=1, username=mengday)System.out.println(user);Map userIdAndUsernameMap = userList.stream().collect(Collectors.toMap(User::getId, User::getUsername));String username = userIdAndUsernameMap.get(1L);// mengdaySystem.out.println(username);}16. 集合元素拼接
@Testpublic void testJoining(){ // a,b,c List list2 = Arrays.asList("a", "b", "c"); String result = list2.stream().collect(Collectors.joining(",")); // Collectors.joining(",")的結果是:a,b,c 然后再將結果 x + "d"操作, 最終返回a,b,cd String str= Stream.of("a", "b", "c").collect(Collectors.collectingAndThen(Collectors.joining(","), x -> x + "d"));}17. 元素聚合
@Testpublic void test(){ // 求最值 3 List list = Arrays.asList(1, 2, 3); Integer maxValue = list.stream().collect(Collectors.collectingAndThen(Collectors.maxBy((a, b) -> a - b), Optional::get)); // 最小值 1 Integer minValue = list.stream().collect(Collectors.collectingAndThen(Collectors.minBy((a, b) -> a - b), Optional::get)); // 求和 6 Integer sumValue = list.stream().collect(Collectors.summingInt(item -> item)); // 平均值 2.0 Double avg = list.stream().collect(Collectors.averagingDouble(x -> x));}@Testpublic void test(){// 映射:先對集合中的元素進行映射,然后再對映射的結果使用Collectors操作 // A,B,C Stream.of("a", "b", "c").collect(Collectors.mapping(x -> x.toUpperCase(), Collectors.joining(",")));}18. 分組
public class User { private Long id; private String username; private Integer type; // Getter & Setter & toString}@Testpublic void testGroupBy(){ List list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // 奇偶數分組:奇數分一組,偶數分一組 // groupingBy(Function super T, ? extends K> classifier) 參數是Function類型,Function返回值可以是要分組的條件,也可以是要分組的字段 // 返回的結果是Map,其中key的數據類型為Function體中計算類型,value是List類型,為分組的結果 Map> result = list.stream().collect(Collectors.groupingBy(item -> item % 2 == 0)); // {false=[1, 3, 5, 7, 9], true=[2, 4, 6, 8, 10]} System.out.println(result); // partitioningBy 用于分成兩組的情況 Map> twoPartiton = list.stream().collect(Collectors.partitioningBy(item -> item % 2 == 0)); System.out.println(twoPartiton); User user = new User(1L, "zhangsan", 1); User user2 = new User(2L, "lisi", 2); User user3 = new User(3L, "wangwu", 3); User user4 = new User(4L, "fengliu", 1); List users = Arrays.asList(user, user2, user3, user4); // 根據某個字段進行分組 Map> userGroup = users.stream().collect(Collectors.groupingBy(item -> item.type)); /** * key 為要分組的字段 * value 分組的結果 * { * 1=[User{id=1, username='zhangsan', type=1}, User{id=4, username='fengliu', type=1}], * 2=[User{id=2, username='lisi', type=2}], * 3=[User{id=3, username='wangwu', type=3}] * } */ System.out.println(userGroup);} // 分組并對分組中的數據統計@Testpublic void testGroupBy2() { Foo foo1 = new Foo(1, 2); Foo foo2 = new Foo(2, 23); Foo foo3 = new Foo(2, 6); List list = new ArrayList<>(4); list.add(foo1); list.add(foo2); list.add(foo3); Map collect = list.stream().collect(Collectors.groupingBy(Foo::getCode, Collectors.summarizingInt(Foo::getCount))); IntSummaryStatistics statistics1 = collect.get(1); IntSummaryStatistics statistics2 = collect.get(2); System.out.println(statistics1.getSum()); System.out.println(statistics1.getAverage()); System.out.println(statistics1.getMax()); System.out.println(statistics1.getMin()); System.out.println(statistics1.getCount()); System.out.println(statistics2.getSum()); System.out.println(statistics2.getAverage()); System.out.println(statistics2.getMax()); System.out.println(statistics2.getMin()); System.out.println(statistics2.getCount());}19.累計操作
@Testpublic void testReducing(){ // sum: 是每次累計計算的結果,b是Function的結果 System.out.println(Stream.of(1, 3, 4).collect(Collectors.reducing(0, x -> x + 1, (sum, b) -> { System.out.println(sum + "-" + b); return sum + b; }))); // 下面代碼是對reducing函數功能實現的描述,用于理解reducing的功能 int sum = 0; List list3 = Arrays.asList(1, 3, 4); for (Integer item : list3) { int b = item + 1; System.out.println(sum + "-" + b); sum = sum + b; } System.out.println(sum); // 注意reducing可以用于更復雜的累計計算,加減乘除或者更復雜的操作 // result = 2 * 4 * 5 = 40 System.out.println(Stream.of(1, 3, 4).collect(Collectors.reducing(1, x -> x + 1, (result, b) -> { System.out.println(result + "-" + b); return result * b; })));}本號致力于讓大家能夠學到實用的知識,如果您認為寫的不好請在下方評論提出您的建議,如果您認為寫的好請給個贊。
總結
以上是生活随笔為你收集整理的c++ 11新特性总结_JDK1.8新特性Stream和Collectors19个常用示例总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 显示部分x_Linux 黑话解释:什么是
- 下一篇: 怎么让员工服从管理_面对员工抬杠,情绪负