Java8 new features - Stream API

Stream processing is a key abstractions Java8 collection, you can specify that you want it to be a set of operations can be performed very complex search, filtering and mapping data and other operations. Use Stream API over the collection operation, it is similar to using a SQL database operations performed. Stream API may be used to perform operations in parallel. Briefly, Stream API provides an efficient and easy to use way of processing data.

What is Stream

Is a data channel, the data source for the operation (set, arrays, etc.) of the generated element sequence
set talking about the data stream is to calculate the stresses

PS:

  • Stream elements themselves are not stored
  • Stream does not change the source object, on the contrary, they will return the result of holding a new Stream
  • Stream operation is performed delayed, which means they will only need to wait until the results of the implementation of

The following graph may reflect the more intuitive process:

  • Stream create
    a data source (arrays, collections, etc.), obtaining a stream
  • Intermediate operating
    a chain intermediate operation, the data processing of the data source
  • Terminate the operation (operation terminal)
    a termination operation, performing the intermediate operation chain, and produce results

Creating Stream

stream provided by the Collection series collection () or parallelStream ()

The Java8 Collection interface is extended to provide a method of obtaining two streams:

  • default Stream stream (): returns a sequential stream
  • default Stream parallelStream (): returns a parallel stream

Sample code:

List<Integer> list = new ArrayList<>();
Stream<Integer> stream1 = list.stream();
Stream<Integer> stream2 = list.parallelStream();

Created by an array of stream

Arrays static method of the stream Java8 () to get the data stream

  • static Stream stream (T [] arrays): Returns a stream

Sample code:

Integer[] integers = new Integer[10];
Stream<Integer> stream = Arrays.stream(integers);

Created by value stream

of (), create a flow value through the display, it can be any number of parameters received by the Stream class Static method

  • public static Stream of (T ... values): Returns a stream

Sample code:

Stream<Integer> stream = Stream.of(1, 2, 3);

Create an unlimited stream

Use the static method Stream.iterate () and Stream.generate (), create an unlimited stream

  • Iteration: public static Stream iterate(final T seed, final UnaryOperator f)
  • Generation: public static Stream generate(Supplier s)

Sample code:

// 迭代
Stream stream1 = Stream.iterate(0, (x) ->  x + 2);
// 生成
Stream stream2 = Stream.generate(() -> Math.random());

Intermediate operation

A plurality of intermediate operations may be joined to form a pipeline , the pipeline operation unless the terminating trigger, or the intermediate operation does not perform any process ! In all at once stopping operation process, called "lazy evaluation" .

Screening and sliced

  • filter: search binding lambda, excluded from the flow element
  • limit: Truncated stream, so that the element does not exceed a given number of
  • skip (n): skipped element, a return flow removed first n elements; if n is less than a flow element, an empty stream; complementary to the limit (n)
  • distinct: screening, hashCode stream generated by the elements () and equals () element deduplication

Sample code:

public class TestStreamApi {
    private static List<Demo> demoList = Arrays.asList(
            new Demo(1, "哈哈哈"),
            new Demo(2, "嘿嘿嘿嘿"),
            new Demo(3, "呵呵呵"),
            new Demo(4, "恩恩恩恩"),
            new Demo(5, "哼哼哼"),
            new Demo(6, "啧啧啧"),
            new Demo(5, "哼哼哼"),
            new Demo(8, "哼")
    );

    public static void main(String[] args) {
        // 中间操作不会执行任何操作
        Stream<Demo> demoStream = demoList.stream()
                .filter((x) -> x.getRemark().length() == 3)
                .limit(4)
                .skip(1)
                .distinct();

        // 终止操作一次性执行全部内容
        // 内部迭代:迭代操作由Stream API完成
        demoStream.forEach(System.out::println);
    }
}

Run Results:
3- oh oh
5- hum hum
6- tut tut

Note: DISTINCT hashCode by screening the generated elementary stream () and equals () deduplication element, it is necessary to rewrite the Demo hashCode () and equals () methods.

Mapping

  • map: receiving Lambda, converting an element to extract information or other form; receiving a function as a parameter, the function will be applied to each element, and maps it into a new element
  • flatMap: receiving a function as a parameter, the value of each stream are replaced with another stream, then all streams into one stream connection

Sample code:

public class TestStreamApi {
    private static List<Demo> demoList = Arrays.asList(
            new Demo(1, "哈哈哈"),
            new Demo(2, "嘿嘿嘿嘿")
    );

    public static void main(String[] args) {
        demoList.stream()
                .map(Demo::getRemark)
                .flatMap(TestStreamApi :: filterCharacter)
                .forEach(System.out::println);
    }

    public static Stream<Character> filterCharacter(String str) {
        List<Character> list = new ArrayList<>();
        for (Character c : str.toCharArray()) {
            list.add(c);
        }
        return list.stream();
    }
}

The result:
Ha
ha
ha
hey
hey
hey
hey

Sequence

  • sorted (): natural ordering
  • sorted (Comparator c): custom sorting

Sample code:

public class TestStreamApi {
    private static List<Demo> demoList = Arrays.asList(
            new Demo(5, "哈哈哈"),
            new Demo(2, "嘿嘿嘿嘿"),
            new Demo(3, "呵呵呵"),
            new Demo(2, "哼哼哼"),
            new Demo(5, "啧啧啧")
    );

    public static void main(String[] args) {
        List<String> list = Arrays.asList("aaa", "bbb", "ccc");
        list.stream()
                .sorted()
                .forEach(System.out::println);
        System.out.println("----------");
        demoList.stream()
                .sorted((x, y) -> {
                    if (x.getNum().equals(y.getNum())) {
                        return x.getRemark().compareTo(y.getRemark());
                    } else {
                        return x.getNum().compareTo(y.getNum());
                    }
                })
                .forEach(System.out::println);
    }
}

Run Results:
AAA
BBB
CCC
----------
2- hum hum
2- Hey Hey
3- oh oh
5- ha
5- tut tut

Termination of operation

Find matches

  • allMatch: check that all the elements match
  • anyMatch: check that all the elements match
  • noneMatch: Check if there is no match for all elements
  • findFirst: returns the first element
  • findAny: Returns the current flow to any element
  • count: Returns the total number of elements in the flow
  • max: maximum value of return flow
  • min: returns the minimum flow

Sample code:

public class TestStreamApi2 {
        private static List<Demo> demoList = Arrays.asList(
            new Demo("张三", 18, 6666.66, Demo.Status.BUSY),
            new Demo("李四", 38, 3333.33, Demo.Status.FREE),
            new Demo("王五", 28, 5555.55, Demo.Status.FREE),
            new Demo("赵六", 48, 7777.77, Demo.Status.BUSY),
            new Demo("王二麻子", 58, 8888.88, Demo.Status.VOCATION)

    );

    public static void main(String[] args) {
        // 是不是所有的对象都处于BUSY状态
        System.out.println(demoList.stream()
                .allMatch((d) -> d.getStatus().equals(Demo.Status.BUSY)));
        // 是否有对象处于BUSY状态
        System.out.println(demoList.stream()
                .anyMatch((d) -> d.getStatus().equals(Demo.Status.BUSY)));
        // 是否没有对象处于BUSY状态
        System.out.println(demoList.stream()
                .noneMatch((d) -> d.getStatus().equals(Demo.Status.BUSY)));
        // 获取工资最高的
        Optional<Demo> optionalDemo1 = demoList.stream()
                .sorted((x, y) -> -Double.compare(x.getSalary(), y.getSalary()))
                .findFirst();
        System.out.println(optionalDemo1.get());
        // 获取随机一个空闲的
        Optional<Demo> optionalDemo2 = demoList.stream()
                .filter((e) -> e.getStatus().equals(Demo.Status.FREE))
                .findAny();
        System.out.println(optionalDemo2.get());
        // 总数
        System.out.println(demoList.stream().count());
        // 工资最高的
        Optional<Demo> optionalDemo3 = demoList.stream()
                .max((x, y) -> Double.compare(x.getSalary(), y.getSalary()));
        System.out.println(optionalDemo3.get());
        // 最小的工资
        Optional<Double> optionalDemo4 = demoList.stream()
                .map(Demo::getSalary)
                .max(Double::compare);
        System.out.println(optionalDemo4.get());
    }
}

class Demo{
    // 姓名
    String name;
    // 年龄
    Integer age;
    // 工资
    Double salary;
    // 状态
    Status status;

    public Demo() {}

    public Demo(String name, Integer age, Double salary, Status status) {
        this.name = name;
        this.age = age;
        this.salary = salary;
        this.status = status;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Double getSalary() {
        return salary;
    }

    public void setSalary(Double salary) {
        this.salary = salary;
    }

    public Status getStatus() {
        return status;
    }

    public void setStatus(Status status) {
        this.status = status;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Demo demo = (Demo) o;
        return name.equals(demo.name) &&
                age.equals(demo.age) &&
                salary.equals(demo.salary) &&
                status == demo.status;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age, salary, status);
    }

    @Override
    public String toString() {
        return "Demo{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", salary=" + salary +
                ", status=" + status +
                '}';
    }

    public enum Status{
        FREE,
        BUSY,
        VOCATION
    }
}

Run Results:
to false
to true
to false
Demo {name = 'King pock', Age = 58, the salary = 8888.88, Status = Vocation}
Demo {name = 'John Doe', Age = 38 is, the salary = 3333.33, Status = the FREE}
. 5
demo {name = 'King pock', Age = 58, the salary = 8888.88, Vocation} Status =
8888.88

Reduction

  • reduce (T identify, BinaryOperator) / reduce (BinaryOperator): stream may be repeated elements combine to give a value

Sample code:

public class TestStreamApi3 {
    private static List<Demo> demoList = Arrays.asList(
            new Demo("张三", 18, 6666.66, Demo.Status.BUSY),
            new Demo("李四", 38, 3333.33, Demo.Status.FREE),
            new Demo("王五", 28, 5555.55, Demo.Status.FREE),
            new Demo("赵六", 48, 7777.77, Demo.Status.BUSY),
            new Demo("王二麻子", 58, 8888.88, Demo.Status.VOCATION)
    );

    public static void main(String[] args) {
        Optional<Double> optional = demoList.stream()
                .map(Demo::getSalary)
                .reduce(Double::sum);
        System.out.println(optional.get());
    }
}

The result:
32222.190000000002

collect

  • collect: the stream is converted to other forms. Collection receiving interface to implement a process to make elements Stream Summary for

Implementation method Collectors interface determines how convection do the collection (such as collect List, Set, Map).

  • toList: The flow element to collect List
  • toSet: the flow elements collected Set
  • toCollection: the stream of elements of the collection to create the collection
  • counting: count the number of elements in the stream
  • Summing integer attribute convection elements: summingInt
  • averagingInt: average calculation stream attribute element Integer
  • summarizingInt: Integer property statistics collection stream
  • jioning: connection flow in each string
  • maxBy: The maximum value is selected comparator
  • minBy: The minimum value is selected comparator
  • reducing: beginning from one accumulator as an initial value, and the elementary stream using BinaryOperator individually binding to a single value statute
  • collectingAndThen: wrapping a further accumulator, the result of its transfer function
  • groupingBy: The value of an attribute convection packet attribute is K, the result is V
  • partitioningBy: partition based on true, false

Sample code:

public class TestStreamApi4 {
    private static List<Demo> demoList = Arrays.asList(
            new Demo("张三", 18, 6666.66, Demo.Status.BUSY),
            new Demo("李四", 38, 3333.33, Demo.Status.FREE),
            new Demo("王五", 28, 5555.55, Demo.Status.FREE),
            new Demo("赵六", 48, 7777.77, Demo.Status.BUSY),
            new Demo("王二麻子", 58, 8888.88, Demo.Status.VOCATION)
    );

    public static void main(String[] args) {
        HashSet<String> set = demoList.stream()
                .map(Demo::getName)
                .collect(Collectors.toCollection(HashSet::new));
        set.forEach(System.out::println);
        // 总数
        System.out.println(demoList.stream()
                .collect(Collectors.counting()));

        // 工资平均值
        System.out.println(demoList.stream()
                .collect(Collectors.averagingDouble(Demo::getSalary)));
    }
}

The result:
John Doe
John Doe
king, pock
Wang Wu
Zhao six
5
6444.438

Guess you like

Origin www.cnblogs.com/fx-blog/p/11745205.html