Java Stream流操作

 Java8 流操作

package com.lyc.designpatterns.stream;

import lombok.AllArgsConstructor;
import lombok.Data;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamDemo {

    public static void main(String[] args) {
        List list = new ArrayList<>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(6);
        list.add(6);

        // 过滤
        List collect = list.stream().filter(temp -> temp != 1).collect(Collectors.toList());
        System.out.println(collect.toString());

        List people = new ArrayList<>();
        people.add(new Person("张三", "男", 1));
        people.add(new Person("张1", "女", 2));
        people.add(new Person("张2", "男", 3));
        people.add(new Person("张3", "女", 5));
        people.add(new Person("张4", "男", 7));
        people.add(new Person("张5", "女", 4));
        // 取第一个值
        System.out.println(people.stream().findFirst().get());
        System.out.println("============================");

        // 分页
        people.stream().limit(1).forEach(System.out::println);
        System.out.println("============================");
        // 排序  正序
        people.stream().sorted(Comparator.comparing(Person::getAge)).forEach(System.out::println);
        System.out.println("============================");
        // 排序  倒叙
        people.stream().sorted(Comparator.comparing(Person::getAge).reversed()).forEach(System.out::println);
        System.out.println("============================");

        // 组合
        String s = people.stream().map(Person::getName).reduce((a, b) -> a + b).get();
        System.out.println(s);
        System.out.println("============================");

        // 去重
        people.stream().distinct().forEach(System.out::println);
        System.out.println("============================");

        // 收集名称叫张三的数据
        List collect1 = people.stream()
                .filter(x -> x.getName().equals("张三")).collect(Collectors.toList());
        System.out.println(collect1.size());
        collect1.stream().forEach(temp-> System.out.println(temp));
        System.out.println("============================");

        // 收集男的数据
        List collect2 = people.stream()
                .filter(f -> "男".equals(f.getGender()))
                .map(Person::getName)
                .collect(Collectors.toList());
        System.out.println(collect2);
        System.out.println("============================");

    }

}

@Data
@AllArgsConstructor
class Person {
    private String name;//姓名
    private String gender;//性别
    private Integer age;//性别
}

你可能感兴趣的:(Java基础,java)