JDK新特性-创新互联

JDK1.5新特性

JDK1.5的新特性:

自动拆装箱 , 泛型 , 增强for , 静态导入 , 可变参数 , 枚举

枚举概述: 就是一个类只能存在几个固定的对象,那么这个就是枚举.我们就可以使用这些对象可以表示一些固定的值.
举例:一周只有7天,一年只有12个月等。

成都创新互联公司是专业的冀州网站建设公司,冀州接单;提供网站建设、成都网站设计,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行冀州网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!
枚举

定义枚举类要用关键字enum
所有枚举类都是Enum的子类
枚举类的第一行上必须是枚举项,最后一个枚举项后的分号是可以省略的,但是如果枚举类有其他的东西,这个分号就不能省略。建议不要省略
枚举类可以有构造器,但必须是private的,它默认的也是private的。枚举项的用法比较特殊:枚举(“”);
枚举类也可以有抽象方法,但是枚举项必须重写该方法
枚举在switch语句中的使用

枚举类的常见方法

int ordinal() 返回枚举项的序号
int compareTo(E o) 比较两个枚举项的 返回的是两个枚举项序号的 差值
String name() 获取枚举项的名称
String toString()获取枚举项的名称
<T> T valueOf(Class<T> type,String name) 用来获取指定的枚举项 参数1:枚举类对应的字节码对象 参数2 枚举项的名称
values() 获取所有的枚举项
此方法虽然在JDK文档中查找不到,但每个枚举类都具有该方法,它遍历枚举类的所有枚举值非常方便

列(枚举):
  • 1:
    public static void main(String[] args) {

    // 测试
    Direction front = Direction.FRONT ;
    Direction behind = Direction.BEHIND;
    Direction left = Direction.LEFT ;
    Direction right = Direction.RIGHT ;

    System.out.println(front.ordinal());
    System.out.println(behind.ordinal());
    System.out.println(left.ordinal());
    System.out.println(right.ordinal());

    System.out.println("----------------------------------");

    System.out.println(front.compareTo(right));

    System.out.println("----------------------------------");

    System.out.println(front.name());

    System.out.println("----------------------------------");

    System.out.println(front.toString());
    System.out.println(front);

    System.out.println("----------------------------------");

    // <T> T valueOf(Class<T> type,String name): 用来获取指定的枚举项
    // type: 表示的是对应的枚举的字节码文件对象
    // name: 就是枚举项的名称
    Direction direction = Direction.valueOf(Direction.class, "RIGHT") ;
    System.out.println(direction);

    System.out.println("----------------------------------");

    Direction[] directions = Direction.values() ;

    for(Direction d : directions){
    System.out.println(d);
    }

}

  • 2
    public enum Direction {
    FRONT("前"), AFTER("后"), LEFT("后"),RIGHT("右"); //下面如果有代码,; 分号不要省略,每个枚举项,用逗号隔开
    private Direction(String name){}
    }

//public class Direction {
// //表示前后左右四个固定的值
// //ctrl+shift+U 转换大小写
// public static final org.westos.demo8.Direction FRONT = new org.westos.demo8.Direction("前");
// public static final org.westos.demo8.Direction AFTER = new org.westos.demo8.Direction("后");
// public static final org.westos.demo8.Direction LEFT = new org.westos.demo8.Direction("左");
// public static final org.westos.demo8.Direction RIGHT = new org.westos.demo8.Direction("右");
// public String name;
//
// private Direction(String name) {
// this.name = name;
// }
//}
public class MyTest {
public static void main(String[] args) {
Direction front = Direction.FRONT;
Direction after = Direction.AFTER;
Direction left = Direction.LEFT;
Direction right = Direction.RIGHT;
System.out.println(front.toString());
System.out.println(after);
System.out.println(left);
System.out.println(right);

long num = 10_000_000_000L; //_充当千位分割符

   //JUI JavaEE  B/S
   //C/S

}

}

JDK1.7新特性

二进制字面量
JDK7开始,终于可以用二进制来表示整数(byte,short,int和long)。
使用二进制字面量的好处是,可以使代码更容易被理解。语法非常简单,只要在二进制数值前面加 0b或者0B
int x = 0b110110
数字字面量可以出现下划线

为了增强对数值的阅读性,如我们经常把数据用逗号分隔一样。JDK7提供了_对数据分隔。
举例:
int x = 100_1000;
注意事项:
不能出现在进制标识和数值之间
不能出现在数值开头和结尾
不能出现在小数点旁边

switch 语句可以用字符串
泛型可以简化
异常的多个catch可以合并

JDK1.8新特性

新增的日期时间API
LocalDate、 LocalTime、 LocalDateTime类

LocalDate、 LocalTime、 LocalDateTime类的实例是不可变的对象,分别表示使用 ISO-8601日历系统的日期、时间、日期和时间它们提供了简单的日期或时间,并不包含当前的时间信息。也不包含与时区相关的信息。
注: ISO-8601日历系统是国际标准化组织制定的现代公民的日期和时间的表示法
这些新增的日期时间API都在 java.time包下

获取对象的方法

1通过静态方法 now();
例如:LocalDateTime ldt = LocalDateTime.now();

方式2通过静态方法of()方法参数可以指定年月日时分秒
    例如:LocalDateTime of = LocalDateTime.of(2018, 12, 30, 20, 20, 20);
常用方法
1.与获取相关的方法:get系类的方法
    ldt.getYear();获取年
    ldt.getMinute();获取分钟
    ldt.getHour();获取小时
    getDayOfMonth 获得月份天数(1-31)
    getDayOfYear 获得年份天数(1-366)
    getDayOfWeek 获得星期几(返回一个 DayOfWeek枚举值)
    getMonth 获得月份, 返回一个 Month 枚举值
    getMonthValue 获得月份(1-12)
    getYear 获得年份
2.格式化日期日期字符串的方法 format()
    例如:String yyyy = ldt.format(DateTimeFormatter.ofPattern("yyyy"));
3.转换的方法 toLocalDate();toLocalTime();
    例如:LocalDate localDate = ldt.toLocalDate();
    例如:LocalTime localTime = ldt.toLocalTime();
4.判断的方法
    isAfter()判断一个日期是否在指定日期之后
    isBefore()判断一个日期是否在指定日期之前
    isLeapYear()判断是否是闰年注意是LocalDate类中的方法
        例如:  boolean after = ldt.isAfter(LocalDateTime.of(2024, 1, 1, 2, 3));
        例如  boolean b= LocalDate.now().isLeapYear();

5.解析的静态方法parse("2007-12-03T10:15:30");
    paser() 将一个日期字符串解析成日期对象,注意字符串日期的写法的格式要正确,否则解析失败
        例如:LocalDateTime parse = LocalDateTime.parse("2007-12-03T10:15:30");

    按照我们指定的格式去解析:

    注意细节:如果用LocalDateTime 想按照我们的自定义的格式去解析,注意
    日期字符串的 年月日时分秒要写全,不然就报错
        LocalDateTime ldt4 = LocalDateTime.now();
        DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime.parse("2018-01-21 20:30:36", formatter2);

6.添加年月日时分秒的方法 plus系列的方法 都会返回一个新的LocalDateTime的对象
    LocalDateTime localDateTime = ldt.plusYears(1);
    LocalDateTime localDateTime1 = ldt.plusMonths(3);
    LocalDateTime localDateTime2=ldt.plusHours(10);
7.减去年月日时分秒的方法 minus 系列的方法 注意都会返回一个新的LocalDateTime的对象
    例如:LocalDateTime localDateTime2 = ldt.minusYears(8);
8.指定年月日时分秒的方法 with系列的方法 注意都会返回一个新的LocalDateTime的对象
    例如 LocalDateTime localDateTime3 = ldt.withYear(1998);
      //获取这个月的第几个星期几是几号,比如 TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY) 代表的意思是这个月的第二个星期五是几号
          // TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.FRIDAY)
          LocalDateTime with2 = now.with(TemporalAdjusters.dayOfWeekInMonth(2,DayOfWeek.FRIDAY));

Instant时间戳类从1970-01-01 00:00:00 截止到当前时间的毫秒值

1获取对象的方法 now()
注意默认获取出来的是当前的美国时间和我们相差八个小时
Instant ins = Instant.now();
System.out.println(ins);
我们在东八区 所以可以加8个小时 就是我们的北京时间

  1. Instant中设置偏移量的方法:atOffset() 设置偏移量
    OffsetDateTime time = ins.atOffset(ZoneOffset.ofHours(8));
    System.out.println(time);
    3.获取系统默认时区时间的方法atZone()
    方法的参数是要一个时区的编号可以通过时区编号类获取出来
    ZoneId.systemDefault()获取本地的默认时区ID
    ZonedDateTime zonedDateTime = ins.atZone(ZoneId.systemDefault());
    System.out.println(zonedDateTime);
    4.get系列的方法

    getEpochSecond() 获取从1970-01-01 00:00:00到当前时间的秒值
    getNano()方法是把获取到的当前时间的秒数 换算成纳秒
    long epochSecond = ins.getEpochSecond();//获取从1970-01-01 00:00:00到当前时间的秒值
    getNano()方法是把获取到的当前时间的豪秒数 换算成纳秒 比如当前时间是2018-01-01 14:00:20:30
    那就把30豪秒换算成纳秒 int nano = ins.getNano();

  2. ofEpochSecond()方法 给计算机元年增加秒数
    例如 Instant instant = Instant.ofEpochSecond(5);
    System.out.println(instant);
    单位换算
    0.1 毫秒 = 10 的5次方纳秒 = 100000 纳秒
    1 毫秒 = 1000 微妙 = 1000000 纳秒

    Duration : 用于计算两个“时间”间隔的类

    Period : 用于计算两个“日期”间隔的类

    列如:

    Duration类中静态方法between()
    Instant start = Instant.now();
    for(int i=0;i<1000L;i++){
    System.out.println("循环内容");
    }
    Instant end = Instant.now();
    静态方法:between() 计算两个时间的间隔,默认是秒
    Duration between = Durati’on.between(start, end);
    Duration中的toMillis()方法:将秒转成毫秒
    System.out.println(between.toMillis());

Period类 中的静态方法between()
计算两个日期之间的间隔
LocalDate s = LocalDate.of(1985, 03, 05);
LocalDate now = LocalDate.now();
Period be = Period.between(s, now);
System.out.println(be.getYears());间隔了多少年
System.out.println(be.getMonths());间隔了多少月
System.out.println(be.getDays());间隔多少天

TemporalAdjuster : 时间校正器,是个接口,

一般我们用该接口的一个对应的工具类 TemporalAdjusters中的一些常量,来指定日期

例如:

LocalDate now = LocalDate.now();
System.out.println(now);
1 使用TemporalAdjusters自带的常量来设置日期
LocalDate with = now.with(TemporalAdjusters.lastDayOfYear());
System.out.println(with);
2 采用TemporalAdjusters中的next方法来指定日期
LocalDate date = now.with(TemporalAdjusters.next(DayOfWeek.SUNDAY));
System.out.println(date);
例如:TemporalAdjusters.next(DayOfWeek.SUNDAY) 本周的星期天
例如:TemporalAdjusters.nextOrSame(DayOfWeek.MONDAY) 下一周的星期一
3 采用自定义的方式来指定日期 比如指定下个工作日
LocalDateTime ldt = LocalDateTime.now();
LocalDateTime workDay = ldt.with(new TemporalAdjuster() {@Override
br/>@Override
//向下转型
LocalDateTime ld = (LocalDateTime) temporal;
//获取这周的星期几
DayOfWeek dayOfWeek = ld.getDayOfWeek();
if (dayOfWeek.equals(DayOfWeek.FRIDAY)) {
return ld.plusDays(3);//如果这天是星期五,那下个工做日就加3天
} else if (dayOfWeek.equals(DayOfWeek.SATURDAY)) {
return ld.plusDays(2);//如果这天是星期六,那下个工做日就加2天
} else {
//其他就加一天
return ld.plusDays(1);
}
}
});

System.out.println(workDay);

DateTimeFormatter :解析和格式化日期或时间的类

1.获取对象的方式,通过静态方法ofPattern("yyyy-MM-dd");
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDateTime now = LocalDateTime.now();
2.format()方法把一个日期对象的默认格式 格式化成指定的格式
String format1 = dateFormat.format(now);
System.out.println(format1);
3.格式化日期 方式2使用日期类中的format方法 传入一个日期格式化类对象

LocalDateTime now1 = LocalDateTime.now();
使用日期类中的format方法 传入一个日期格式化类对象
使用DateTimeFormatter中提供好的日期格式常量
now1.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);

4.使用自定义的日期格式格式化字符串
DateTimeFormatter timeFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");//自定义一个日期格式
String time = now1.format(timeFormat);
System.out.println(time);

  1. 把一个日期字符串转成日期对象
    使用日期类中的parse方法传入一个日期字符串,传入对应的日期格式化类
    DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    LocalDateTime parse = LocalDateTime.parse(time, timeFormat);
    System.out.println(parse);

    ZonedDate,ZonedTime、ZonedDateTime : 带时区的时间或日期

    用法和 LocalDate、 LocalTime、 LocalDateTime 一样 只不过ZonedDate,ZonedTime、ZonedDateTime 这三个带有当前系统的默认时区

    ZoneID 世界时区类

    1.获取世界各个地方的时区的集合 的方法getAvailableZoneIds()
    使用ZoneID中的静态方法getAvailableZoneIds();来获取
    例如:Set<String> availableZoneIds = ZoneId.getAvailableZoneIds();
    2.获取系统默认时区的ID
    ZoneId zoneId = ZoneId.systemDefault(); //Asia/Shanghai
    3.获取带有时区的日期时间对象
    //创建日期对象
    LocalDateTime now = LocalDateTime.now();
    //获取不同国家的日期时间根据各个地区的时区ID名创建对象
    ZoneId timeID = ZoneId.of("Asia/Shanghai");
    //根据时区ID获取带有时区的日期时间对象
    ZonedDateTime time = now.atZone(timeID);
    System.out.println(time);
    //方式2 通过时区ID 获取日期对象
    LocalDateTime now2 = LocalDateTime.now(ZoneId.of("Asia/Shanghai"));
    System.out.println(now2);

    Lambda表达式

    Lambda 是一个匿名函数,我们可以把 Lambda表达式理解为是一段可以传递的代码(将代码像数据一样进行传递)。可以写出更简洁、更灵活的代码。作为一种更紧凑的代码风格,使Java的语言表达能力得到了提升。
    public interface MyInterface {
    void show(int a,int b);
    }
    public class MyTest {
    public static void main(String[] args) {
    //JDK1.8之后提供了一种新的语法 叫做 Lambda表达式,可以简化我们对匿名内部类的写法,也可以作为参数传递
    //可以使用匿名内部类来创建该接口的一个子类对象
    MyInterface myInterface = new MyInterface() {@Override
    br/>@Override
    System.out.println(a + b);
    }
    };
    myInterface.show(10, 20);
    //上面匿名内部类的写法,我可以用Lambda表达式来简化
    //Lambda 引入了一个箭头 -> 符号,将我们的表达式分为左右两部分
    //箭头左边,就是接口中抽象方法的参数列表,箭头右边,是你对接口中的抽象方法的具体的重写逻辑
    //参数列表中的数据类型 可以省略不写
    MyInterface myInterface3 = (x, y) -> System.out.println(x + y);
    //当然你可以写上参数的,数据类型
    MyInterface myInterface2 = (int x, int y) -> System.out.println(x + y);

    //箭头右边对接口中方法的具体实现逻辑,如果只有一行代码,那么{}也可以省略不写,当然也可以写上
    MyInterface myInterface4 = (int x, int y) -> {
        System.out.println(x + y);
    };
    
    //如果你对接口中的抽象方法的实现逻辑有多条语句,那么这个{} 必须写上
    MyInterface myInterface5 = (int x, int y) -> {
        System.out.println(x + y);
        System.out.println(x-y);
        System.out.println(x*y);
    };
    myInterface2.show(10, 2000);

    }
    }
    public class MyTest2 {
    public static void main(String[] args) {
    MyInterface2 myInterface2 = new MyInterface2() {@Override
    br/>@Override
    return a + b;
    }
    };

    System.out.println("---------------------");
    //如果你对接口中的抽象方法具体的实现逻辑是一行语句,并且还有返回值,那么{}就省略不写
    MyInterface2 myInterface3 = (x, y) -> x + y;
    //如果说你要将return关键字写上,那么你也要将{}写上
    MyInterface2 myInterface4 = (x, y) -> {
        return x + y;
    };
    
    myTest(new MyInterface() {
        @Override
        public void show(int a, int b) {
            System.out.println(a+b);
        }
    });
    MyInterface myInterface=(x, y) -> System.out.println(x + y);
    myTest(myInterface);

    }

    private static void myTest(MyInterface myInterface) {
    myInterface.show(10,20);
    }
    }
    通过上面的对比,发现Lambda表达式式书写起来更为简洁
    那我们具体来看一下Lambda表达式的书写语法
    Lambda 表达式在Java 语言中引入了一个新的语法元素和操作符。这个操作符为 “ ->” , 该操作符被称为 Lambda 操作符或箭头操作符。它将 Lambda 分为两个部分:
    左侧: 指定了 Lambda 表达式需要的所有参数
    右侧: 指定了 Lambda 体,即 Lambda 表达式要执行的功能。
    public interface MyInteface3 {
    void test();
    void show();
    }
    public class MyTest2 {
    public static void main(String[] args) {
    new MyInteface3(){@Override
    br/>@Override

    }
    
        @Override
        public void show() {
    
        }
    };

    //Lambda 需要 函数式接口的支持
    // 函数式接口:这个接口中,仅仅只有 一个抽象方法
    // 函数式接口可以使用注解 @FunctionalInterface 来检测这个接口是不是函数式接口
    //

    }
    }
    public class MyTest3 {
    public static void main(String[] args) {

    Integer[] integers=new Integer[]{10,30,40,1,3,5};
    Arrays.sort(integers, (a, b) -> b-a);
    
    System.out.println(Arrays.toString(integers));

    }
    }
    上述 Lambda 表达式中的参数类型都是由编译器推断得出的。 Lambda 表达式中无需指定类型,程序依然可以编译,这是因为 javac 根据程序的上下文,在后台推断出了参数的类型。 Lambda 表达式的类型依赖于上下文环境,是由编译器推断出来的。这就是所谓的“类型推断”.

    函数式接口

    Lambda表达式就是对函数式接口的一种简写方式,所以只有是函数式接口,我们才能用Lambda表达式.再换句话说,Lambda表达式需要函数式接口的支持,那函数式接口我们可以自己定义,当然JDK1.8也给我们提供了一些现成的函数式接口.

    函数式接口的定义是: 只包含一个抽象方法的接口,称为函数式接口。

    你可以通过 Lambda 表达式来创建该接口的对象
    我们可以在任意函数式接口上使用 @FunctionalInterface 注解,这样做可以检查它是否是一个函数式接口,同时 javadoc 也会包含一条声明,说明这个接口是一个函数式接口.

    Java中提供的4大核心函数式接口

    函数式接口 参数类型 返回类型 用途
    Consumer<T>
    消费型接口 T void 对类型为T的对象应用操
    作,包含方法:
    void accept(T t)
    Supplier<T>
    供给型接口 无 T 返回类型为T的对象,包
    含方法: T get();
    Function<T, R>
    函数型接口
    T R 对类型为T的对象应用操
    作,并返回结果。结果
    是R类型的对象。包含方
    法: R apply(T t);
    Predicate<T> 断言型接口
    T boolean 确定类型为T的对象是否
    满足某约束,并返回
    boolean 值。包含方法
    boolean test(T t);

    其他函数式接口

    函数式接口 参数类型 返回类型 用途
    BiFunction<T,U,R>
    T U R 对类型为 T, U 参数应用
    操作, 返回 R 类型的结
    果。 包含方法为
    R apply(T t, U u);
    UnaryOperator<T>
    (Function的子接口)
    T T 对类型为T的对象进行一
    元运算, 并返回T类型的
    结果。 包含方法为
    T apply(T t);
    BinaryOperator<T>
    (BiFunction的子接口) T T T 对类型为T的对象进行二
    元运算, 并返回T类型的
    结果。 包含方法为
    T apply(T t1, T t2);
    BiConsumer<T,U>
    T U void 对类型为T, U 参数应用
    操作。 包含方法为
    void accept(T t, U u)
    ToIntFunction<T>
    ToLongFunction<T>
    ToDoubleFunction<T>
    T int
    long
    double 分 别 计 算 int 、 long 、
    double、 值的函数
    IntFunction<R>
    LongFunction<R>
    DoubleFunction<R>
    int
    long
    double R 参数分别为int、 long、
    double 类型的函数

    Stream API

    Stream 是 Java8 中处理集合的关键抽象概念,
    它可以指定你希望对集合进行的操作,
    可以执行非常复杂的查找、过滤和映射数据等操作。
    使用Stream API 对集合数据进行操作,就类似于使用 SQL 执行的数据库查询。也可以使用 Stream API 来并行执行操作。
    简而言之,Stream API 提供了一种高效且易于使用的处理数据的方式。

    流到底是什么呢?

    是数据渠道,用于操作数据源(集合、数组等)所生成的元素序列。
    集合讲的是数据,流讲的是计算!

    • 注意:
      ①Stream 自己不会存储元素。
      ②Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
      ③Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。

      steam操作的三个步骤

      Stream 的操作三个步骤
      1.创建 Stream
      一个数据源(如:集合、数组),获取一个流
       2.中间操作
      一个中间操作链,对数据源的数据进行处理
       3.终止操作(终端操作)
      一个终止操作,执行中间操作链,并产生结果

创建Stream的方式

1.Java8 中的 Collection 接口被扩展,提供了
  两个获取流的方法:

 default Stream<E> stream() : 返回一个顺序流
 default Stream<E> parallelStream() : 返回一个并行流
2.Java8 中的 Arrays 的静态方法 stream() 可以获取数组流:
 static <T> Stream<T> stream(T[] array): 返回一个流
重载形式,能够处理对应基本类型的数组:
public static IntStream stream(int[] array)
 public static LongStream stream(long[] array)
 public static DoubleStream stream(double[] array)
3.由值创建流,可以使用静态方法 Stream.of(), 通过显示值创建一个流。它可以接收任意数量的参数。
 public static<T> Stream<T> of(T... values) : 返回一个流
4.由函数创建流:创建无限流可以使用静态方法 Stream.iterate()和Stream.generate(), 创建无限流。
public static<T> Stream<T> iterate(final T seed, finalUnaryOperator<T> f) 迭代
public static<T> Stream<T> generate(Supplier<T> s) 生成

Stream 的中间操作

多个中间操作可以连接起来形成一个流水线,除非流水线上触发终止操作,否则中间操作不会执行任何的处理!
而在终止操作时一次性全部处理,称为“惰性求值”。
    1. 筛选与切片
      filter(Predicate p) 过滤 接收 Lambda , 从流中排除某些元素。
      distinct() 去重,通过流所生成元素的 hashCode() 和 equals() 去除重复元素
      limit(long maxSize) 截断流,使其元素不超过给定数量。
      skip(long n) 跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit(n) 互补
  • 2.映射
    map(Function f) 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素。
    flatMap(Function f) 接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流.
    mapToDouble(ToDoubleFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 DoubleStream。
    mapToInt(ToIntFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 IntStream。
    mapToLong(ToLongFunction f) 接收一个函数作为参数,该函数会被应用到每个元素上,产生一个新的 LongStream。

  • 3.排序
    sorted() 产生一个新流,其中按自然顺序排序 元素实现Compareble接口
    sorted(Comparator comp) 产生一个新流,其中按比较器顺序排序 传入一个比较器

    steam的终止操作

    终端操作会从流的流水线生成结果。其结果可以是任何不是流的值,例如:List、Integer,甚至是 void 。

1.查找与匹配
    allMatch(Predicate p)   检查是否匹配所有元素  比如判断 所有员工的年龄都是17岁 如果有一个不是,就返回false
    anyMatch(Predicate p)   检查是否至少匹配一个元素  比如判断是否有姓王的员工,如果至少有一个就返回true
    noneMatch(Predicate p)  检查是否没有匹配所有元素   比如判断所有员工的工资都是否都是高于3000 如果有一个人低于3000 就返回false
    findFirst()     返回第一个元素  比如获取工资最高的人  或者 获取工资最高的值是
    findAny()       返回当前流中的任意元素   比如随便获取一个姓王的员工
    count() 返回流中元素总数  
    max(Comparator c)   返回流中大值  比如:获取大年龄值
    min(Comparator c)   返回流中最小值  比如:获取最小年龄的值
    forEach(Consumer c) 内部迭代(使用 Collection 接口需要用户去做迭代,称为外部迭代。相反,Stream API 使用内部迭代——它帮你把迭代做了)
2.归约
    reduce(T iden, BinaryOperator b)  参1 是起始值, 参2 二元运算  可以将流中元素反复结合起来,得到一个值。返回 T  比如: 求集合中元素的累加总和 
    reduce(BinaryOperator b) 这个方法没有起始值  可以将流中元素反复结合起来,得到一个值。返回 Optional<T>  , 比如你可以算所有员工工资的总和
    备注:map 和 reduce 的连接通常称为 map-reduce 模式,因 Google 用它来进行网络搜索而出名。
3.收集
    collect(Collector c)    将流转换为其他形式。接收一个 Collector接口的实现,用于给Stream中元素做汇总的方法
    Collector 接口中方法的实现决定了如何对流执行收集操作(如收集到 List、Set、Map)。
    但是 Collectors 实用类提供了很多静态方法,可以方便地创建常见收集器实例,具体方法与实例如下
 4.Collectors 中的方法
    List<T> toList()        把流中元素收集到List   比如把所有员工的名字通过map()方法提取出来之后,在放到List集合中去
        例子:List<Employee> emps= list.stream().map(提取名字).collect(Collectors.toList());
    Set<T>  toSet()     把流中元素收集到Set  比如把所有员工的名字通过map()方法提取出来之后,在放到Set集合中去
        例子:Set<Employee> emps= list.stream().collect(Collectors.toSet());
    Collection<T> toCollection()        把流中元素收集到创建的集合 比如把所有员工的名字通过map()方法提取出来之后,在放到自己指定的集合中去
        例子:Collection<Employee>emps=list.stream().map(提取名字).collect(Collectors.toCollection(ArrayList::new));
    Long counting()     计算流中元素的个数
        例子:long count = list.stream().collect(Collectors.counting());
    Integer summingInt()    对流中元素的整数属性求和
        例子:inttotal=list.stream().collect(Collectors.summingInt(Employee::getSalary));
    Double averagingInt()       计算流中元素Integer属性的平均值
        例子:doubleavg= list.stream().collect(Collectors.averagingInt(Employee::getSalary));
    IntSummaryStatistics summarizingInt()   收集流中Integer属性的统计值。
        例子:DoubleSummaryStatistics dss= list.stream().collect(Collectors.summarizingDouble(Employee::getSalary));
           从DoubleSummaryStatistics 中可以获取大值,平均值等
                                    double average = dss.getAverage();
                    long count = dss.getCount();
                            double max = dss.getMax();
    String joining() 连接流中每个字符串  比如把所有人的名字提取出来,在通过"-"横杠拼接起来
        例子:String str= list.stream().map(Employee::getName).collect(Collectors.joining("-"));
    Optional<T> maxBy() 根据比较器选择大值  比如求大工资
        例子:Optional<Emp>max= list.stream().collect(Collectors.maxBy(comparingInt(Employee::getSalary)));
    Optional<T> minBy() 根据比较器选择最小值  比如求最小工资
        例子:Optional<Emp> min = list.stream().collect(Collectors.minBy(comparingInt(Employee::getSalary)));
    归约产生的类型 reducing() 从一个作为累加器的初始值开始,利用BinaryOperator与流中元素逐个结合,从而归约成单个值
        例子:inttotal=list.stream().collect(Collectors.reducing(0, Employee::getSalar, Integer::sum));
    转换函数返回的类型 collectingAndThen()       包裹另一个收集器,对其结果转换函数
        例子:inthow= list.stream().collect(Collectors.collectingAndThen(Collectors.toList(), List::size));
    Map<K, List<T>> groupingBy() 根据某属性值对流分组,属性为K,结果为V  比如按照 状态分组
        例子:Map<Emp.Status, List<Emp>> map= list.stream().collect(Collectors.groupingBy(Employee::getStatus));
    Map<Boolean, List<T>> partitioningBy() 根据true或false进行分区 比如 工资大于等于6000的一个区,小于6000的一个区
        例子:Map<Boolean,List<Emp>>vd= list.stream().collect(Collectors.partitioningBy(Employee::getSalary));

并行流与串行流

并行流就是把一个内容分成多个数据块,并用不同的线程分别处理每个数据块的流。
Java 8 中将并行进行了优化,我们可以很容易的对数据进行并行操作。
Stream API 可以声明性地通过 parallel() 与sequential() 在并行流与顺序流之间进行切换。

列子:

public Employee() {
}

public Employee(String name) {
    this.name = name;
}

public Employee(String name, int age) {
    this.name = name;
    this.age = age;
}

public Employee(int id, String name, int age, double salary) {
    this.id = id;
    this.name = name;
    this.age = age;
    this.salary = salary;
}

public Employee(int id, String name, int age, double salary, Status status) {
    this.id = id;
    this.name = name;
    this.age = age;
    this.salary = salary;
    this.status = status;
}

public Status getStatus() {
    return status;
}

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

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

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 double getSalary() {
    return salary;
}

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

public String show() {
    return "测试方法引用!";
}

@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + age;
    result = prime * result + id;
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    long temp;
    temp = Double.doubleToLongBits(salary);
    result = prime * result + (int) (temp ^ (temp >>> 32));
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Employee other = (Employee) obj;
    if (age != other.age)
        return false;
    if (id != other.id)
        return false;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))
        return false;
    return true;
}

@Override
public String toString() {
    return "Employee [id=" + id + ", name=" + name + ", age=" + age + ", salary=" + salary + ", status=" + status
            + "]";
}

//枚举
public enum Status {
    FREE, //空闲
    BUSY, //繁忙
    VOCATION;//休假
}

}
public class MyTest {
public static void main(String[] args) {
//**Stream 的操作三个步骤
//1. 创建 Stream
//一个数据源(如:集合、数组),获取一个流
//2. 中间操作
//一个中间操作链,对数据源的数据进行处理
//3. 终止操作(终端操作)
//一个终止操作,执行中间操作链,并产生结果
//我们会创建流跟集合关联起来,关联起来后,我们是想要使用这个流对集合中的元素,进行一些列的中间操作
//1. 筛选与切片
//filter(Predicate p) 过滤 接收 Lambda ,从流中排除某些元素。
//distinct() 去重,通过流所生成元素的 hashCode () 和 equals () 去除重复元素
//limit( long maxSize)截断流,使其元素不超过给定数量。
//skip( long n)跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit (n) 互补
//

List<Employee> emps = Arrays.asList(
            new Employee(102, "李四", 59, 6666.66),
            new Employee(101, "张三", 18, 9999.99),
            new Employee(103, "王五", 28, 3333.33),
            new Employee(104, "赵六", 8, 7777.77),
            new Employee(104, "赵六", 8, 7777.77),
            new Employee(104, "赵六", 8, 7777.77),
            new Employee(105, "田七", 38, 5555.55)
    );
    //获取流跟集合进行关联
    Stream<Employee> stream = emps.stream();
    //那么我们通过这个流,对集合中的元素进行一些列的中间操作
    //获取工资大于6000块钱的员工
   // Predicate<T> 断言型接口
    Stream<Employee> employeeStream = stream.filter((employee) -> employee.getSalary()>6666);
    //终止操作没有执行,其实中间操作,没有执行
    employeeStream.forEach(System.out::println);
    System.out.println("--------------------------");
    Stream<Employee> stream2 = emps.stream();
    //我要过滤出名字是赵六的员工
    stream2.filter((emp)->emp.getName().equals("赵六")).forEach(System.out::println);

}

}
public class MyTest2 {
public static void main(String[] args) {
//distinct() 去重,通过流所生成元素的 hashCode () 和 equals () 去除重复元素
List<Employee> emps = Arrays.asList(
new Employee(102, "李四", 59, 6666.66),
new Employee(101, "张三", 18, 9999.99),
new Employee(103, "王五", 28, 3333.33),
new Employee(104, "赵六", 8, 7777.77),
new Employee(104, "赵六", 8, 7777.77),
new Employee(104, "赵六", 8, 7777.77),
new Employee(105, "田七", 38, 5555.55)
);

Stream<Employee> stream = emps.stream();
    Stream<Employee> employeeStream = stream.filter((emp) -> emp.getSalary() > 5000);
    Stream<Employee> distinct = employeeStream.distinct();
    distinct.forEach(System.out::println);
}

}
public class MyTest3 {
public static void main(String[] args) {
List<Employee> emps = Arrays.asList(
new Employee(102, "李四", 59, 6666.66),
new Employee(101, "张三", 18, 9999.99),
new Employee(103, "王五", 28, 3333.33),
new Employee(104, "赵六", 8, 7777.771),
new Employee(104, "赵六", 8, 7777.772),
new Employee(104, "赵六", 8, 7777.773),
new Employee(105, "田七", 38, 5555.55)
);

Stream<Employee> stream = emps.stream();
    Stream<Employee> stream1 = stream.filter((emp) -> emp.getName().equals("赵六"));
   // Stream<Employee> limit = stream1.limit(2); //截断流
    //skip( long n)跳过元素,返回一个扔掉了前 n 个元素的流。若流中元素不足 n 个,则返回一个空流。与 limit (n) 互补
    Stream<Employee> skip = stream1.skip(1);//跳过前几个元素,留下剩下的
    skip.forEach(System.out::println);

}

}

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。

网站标题:JDK新特性-创新互联
本文链接:https://www.cdcxhl.com/article30/dooepo.html

成都网站建设公司_创新互联,为您提供虚拟主机服务器托管定制开发移动网站建设动态网站面包屑导航

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都网页设计公司