码迷,mamicode.com
首页 > 编程语言 > 详细

Java有关List的stream基本操作

时间:2018-08-20 21:46:11      阅读:377      评论:0      收藏:0      [点我收藏+]

标签: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-ddddd
d-14-ddddd
d-14-ddddd
temp=[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=[java.util.stream.ReferencePipeline$Head@7cca494b, java.util.stream.ReferencePipeline$Head@7ba4f24f, java.util.stream.ReferencePipeline$Head@3b9a45b3, java.util.stream.ReferencePipeline$Head@7699a589, java.util.stream.ReferencePipeline$Head@58372a00]
collect2=[a, b, c, d, e]
collect3=[a, b, c, d, e]
count:10
item:1
count:11
item:2
count:13
item:3
count:16
item:4
20
11
1,1,2,3
key=a,value=com.demo.Person@1e80bfe81
key=b,value=com.demo.Person@66a298841
key=c,value=com.demo.Person@4769b07b1
key=d,value=com.demo.Person@cc34f4d1
key=e,value=com.demo.Person@17a7cec21
{false=[com.demo.Person@1e80bfe8, com.demo.Person@66a29884, com.demo.Person@4769b07b, com.demo.Person@17a7cec2], true=[com.demo.Person@cc34f4d]}
{a,b,c,d,e}
[1, 2, 3]

待续...

Java有关List的stream基本操作

标签:apt   oid   批量   tag   collect   http   etag   功能   map   

原文地址:https://www.cnblogs.com/xumBlog/p/9507936.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!