Java有關List的stream基本操作

來源:互聯網
上載者:User

標籤:apt   oid   批量   tag   collect   http   etag   功能   map   

參考部落格: https://www.jianshu.com/p/9fe8632d0bc2

Stream簡介
  • Java 8引入了全新的Stream API。這裡的Stream和I/O流不同,它更像具有Iterable的集合類,但行為和集合類又有所不同。
  • stream是對集合對象功能的增強,它專註於對集合對象進行各種非常便利、高效的彙總操作,或者大批量資料操作。
  • 只要給出需要對其包含的元素執行什麼操作,比如 “過濾掉長度大於 10 的字串”、“擷取每個字串的首字母”等,Stream 會隱式地在內部進行遍曆,做出相應的資料轉換。
為什麼要使用Stream
  • 函數式編程帶來的好處尤為明顯。這種代碼更多地表達了商務邏輯的意圖,而不是它的實現機制。易讀的代碼也易於維護、更可靠、更不容易出錯。
  • 高端

有關List的操作,這裡介紹一下stream的用法.

給出Person的代碼, 就是基本的get和set方法.

package com.demo;public class Person {        private String name;    private int age;    private String province;        public Person(String name, int age, String province) {        this.name = name;        this.age = age;        this.province = province;    }        public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String getProvince() {        return province;    }    public void setProvince(String province) {        this.province = province;    }    }

這裡給出Main方法的代碼:

package com.demo;import java.util.ArrayList;import java.util.Arrays;import java.util.List;import java.util.Map;import java.util.Set;import java.util.stream.Collectors;import java.util.stream.Stream;public class Test {    public static void main(String[] args) {                List<Person> list = new ArrayList<Person>();                Person p1 = new Person("a", 11, "aaaaa");        Person p2 = new Person("b", 12, "bbbbb");        Person p3 = new Person("c", 13, "ccccc");        Person p4 = new Person("d", 14, "ddddd");        Person p5 = new Person("e", 15, "eeeee");                list = Arrays.asList(p1, p2, p3, p4, p5);        filterTest(list);        mapTest(list);        flatMapTest(list);        reduceTest();        collectTest(list);    }        private static void println(List<Person> list) {        for(Person p:list) {            System.out.println(p.getName()+"-"+p.getAge()+"-"+p.getProvince());        }    }        // filter age > 13 and name = d     private static void filterTest(List<Person> list) {        List<Person> temp = new ArrayList<Person>();        for(Person p:list) {            if (p.getAge() > 13 && "d".equalsIgnoreCase(p.getName())) {                temp.add(p);            }        }        println(temp);                List<Person> collect = list                .stream()                .filter(p->(p.getAge() > 13 && "d".equalsIgnoreCase(p.getName())))                .collect(Collectors.toList());        println(collect);                List<Person> collect1 = list                .stream()                .filter(p->{                    if (p.getAge() > 13 && "d".equalsIgnoreCase(p.getName())) {                        return true;                    }                    return false;                })                .collect(Collectors.toList());        println(collect1);    }        // map    private static void mapTest(List<Person> list) {        List<String> temp = new ArrayList<>();        for(Person p:list) {            temp.add(p.getName());        }        System.out.println("temp="+temp.toString());                List<String> collect = list                .stream()                .map(p->p.getName())                .collect(Collectors.toList());        System.out.println("collect="+collect);                List<String> collect1 = list                    .stream()                    .map(Person::getName)                    .collect(Collectors.toList());        System.out.println("collect1="+collect1);        List<String> collect2 = list                    .stream()                    .map(p->{                        return p.getName();                    }).collect(Collectors.toList());        System.out.println("collect2="+collect2);    }        // flatMap    private static void flatMapTest(List<Person> list) {        List<String> collect = list                .stream()                .flatMap(person -> Arrays.stream(person.getName().split(" ")))                .collect(Collectors.toList());        System.out.println("collect="+collect);        List<Stream<String>> collect1 = list                    .stream()                .map(person -> Arrays.stream(person.getName().split(" ")))                .collect(Collectors.toList());        System.out.println("collect1="+collect1);           List<String> collect2 = list                    .stream()                .map(person -> person.getName().split(" "))                .flatMap(Arrays::stream)                .collect(Collectors.toList());        System.out.println("collect2="+collect2);        List<String> collect3 = list                    .stream()                .map(person -> person.getName().split(" "))                .flatMap(str -> Arrays.asList(str).stream())                .collect(Collectors.toList());        System.out.println("collect3="+collect3);    }        // reduce    public static void reduceTest(){        Integer reduce = Stream.of(1, 2, 3, 4)                .reduce(10, (count, item) ->{            System.out.println("count:"+count);            System.out.println("item:"+item);            return count + item;        } );        System.out.println(reduce);        Integer reduce1 = Stream.of(1, 2, 3, 4)                .reduce(1, (x, y) -> x + y);        System.out.println(reduce1);        String reduce2 = Stream.of("1", "2", "3")                .reduce("1", (x, y) -> (x + "," + y));        System.out.println(reduce2);    }    /**     * toList     */    public static void collectTest(List<Person> list){        List<String> collect = list.stream()                .map(Person::getName)                .collect(Collectors.toList());                Set<String> collect1 = list.stream()                .map(Person::getName)                .collect(Collectors.toSet());                Map<String, Integer> collect2 = list.stream()                .collect(Collectors.toMap(Person::getName, Person::getAge));        Map<String, String> collect3 = list.stream()                .collect(Collectors.toMap(p->p.getName(), value->{            return value+"1";        }));        for (Map.Entry<String, String> entry : collect3.entrySet()) {                 System.out.println("key=" + entry.getKey() + ",value=" + entry.getValue());            }                //TreeSet<Person> collect4 = list.stream()        //        .collect(Collectors.toCollection(TreeSet::new));        //System.out.println(collect4);                Map<Boolean, List<Person>> collect5 = list.stream()                .collect(Collectors.groupingBy(p->"d".equalsIgnoreCase(p.getName())));        System.out.println(collect5);                String collect6 = list.stream()                .map(p->p.getName())                .collect(Collectors.joining(",", "{", "}"));        System.out.println(collect6);                List<String> collect7 = Stream.of("1", "2", "3").collect(                Collectors.reducing(new ArrayList<String>(), x -> Arrays.asList(x), (y, z) -> {                    y.addAll(z);                    return y;                }));        System.out.println(collect7);    }}

下面是啟動並執行依次結果:

d-14-dddddd-14-dddddd-14-dddddtemp=[a, b, c, d, e]collect=[a, b, c, d, e]collect1=[a, b, c, d, e]collect2=[a, b, c, d, e]collect=[a, b, c, d, e]collect1=[[email protected], [email protected], [email protected], [email protected], [email protected]]collect2=[a, b, c, d, e]collect3=[a, b, c, d, e]count:10item:1count:11item:2count:13item:3count:16item:420111,1,2,3key=a,[email protected]key=b,[email protected]key=c,[email protected]key=d,[email protected]key=e,[email protected]{false=[[email protected], [email protected], [email protected], [email protected]], true=[[email protected]]}{a,b,c,d,e}[1, 2, 3]

待續...

Java有關List的stream基本操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.