首页 > 其他 > 详细

JDK8

时间:2019-10-28 00:18:44      阅读:112      评论:0      收藏:0      [点我收藏+]

集合与lambda表达式:

public class Main {

    static List<String> strList = Arrays.asList("aaaaa", "c", "bbb", "dd", "cc", "eeeeee", "fff", "zzz");
    static List<Integer> integerList = Arrays.asList(4, 5, 6,1, 2, 3,7, 8,8,9,10);
    static List<Integer> intergerList02 = Arrays.asList(100, 200, 300, 400, 500);

    static List<User> userList = new ArrayList<User>(){
        {
            this.add(new User("111", "guo", "111a", 11));
            this.add(new User("222", "xiao", "222b", 22));
            this.add(new User("333", "feng", "333c",23));
            this.add(new User("444", "sadfaf", "444d", 22));
        }
    };

    public static void main(String[] args) {

        streamMethod();

//        doubleColon();
//        iterator();
    }

    /**
     * stream() 方法是定义在 Collection 类的一个方法,返回一个 Stream<E> 流对象
     */
    private static void streamMethod() {
        // mapToInt、mapToLong、mapToDouble
//        mapToIntLongDouble();
//        // distinct 方法
//        distinct();
//        // filter 方法
//        filter();
        // map 方法
//        mapMethod();
//        Main.test01();
//        mapReduce();
        // sort方法、limit方法
        sortLimit();
//        groupingBy();
    }

    /**
     * map 方法里面的那个参数一定是一个lambda表达式  a.toUpperCase() ,如果里面  a.toUpperCase() ,则报错
     * map 方法返回的一样是那个stream流,所以可以继续调用 方法,达到链式反应方法
     */
    private static void mapMethod() {
        // 变大写字母并以逗号分隔的字符串输出;如果Collectors.joining(",")里面没有参数,则输出没有分隔符,很难看哦
        String str = strList.stream().map(a -> a.toUpperCase()).collect(Collectors.joining(","));
        String str02 = strList.stream().map(String::toUpperCase).collect(Collectors.joining(","));
        double bill = intergerList02.stream().map(cost -> cost * 1).map(cost -> cost * 2).reduce((sum, cost) -> sum + cost).get();
//        List<Long> collectList = list.stream().map(i -> i.getId()).collect(Collectors.toList()); // jdk8 从一个对象里面取出一个属性变成集合
        System.out.println(bill);
    }

    /**
     * 集合遍历
     * 箭头左边表示参数
     * 箭头右边一定要是表达式,当里面有多个等式时,一定要用大括号哦
     */
    private static void iterator() {
        strList.forEach(a -> a += "eeee");
        strList.forEach(a -> {
            a += "ddd";
            System.out.println(a += "ddd");
            System.out.println(a + "ccc");
        });
    }


    /**1
     * 对元素进行处理之后,再进行统计;Collectors的方法不能对元素进行处理,要不就要for循环进行遍历
     * Stream<E> 流对象 有 mapToInt、mapToLong、mapToDouble 方法,分别返回 IntStream、LongStream、DoubleStream 对象
     * IntSummaryStatistics 一共有:getMax()、getMin()、getAverage()、getCount()、getSum() 五种方法
     */
    private static void mapToIntLongDouble() {
        IntSummaryStatistics iss = integerList.stream().mapToInt(i -> i + 1).summaryStatistics();
    }

    /**
     * 去重
     */
    private static void distinct() {
        // 有序排列:[4, 5, 6, 1, 2, 3, 7, 8, 9, 10]
        List<Integer> list = integerList.stream().distinct().collect(Collectors.toList());
        // 无序排列:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
        Set<Integer> set = integerList.stream().collect(Collectors.toSet());
    }

    /**
     * 双冒号:对参数不能有修改
     */
    private static void doubleColon() {
        String str = strList.stream().map(String::toUpperCase).collect(Collectors.joining()); // 变大写字母
        int sum = integerList.stream().mapToInt(Integer::intValue).sum(); //求和

    }

    /**
     * 过滤
     */
    private static void filter() {
        List<String> list = strList.stream().filter(i -> i.length() > 2).collect(Collectors.toList()); // 过滤出长度大于2的字符串
        List<Integer> evens = integerList.stream().filter(i -> i % 2 == 0).collect(Collectors.toList()); //过滤出偶数列表
//     RoleType res=Arrays.stream(RoleType.values()).filter(role->role.getCode()==code).findFirst().get();
    }

    /**
     * 对里面的值处理再相加
     */
    private static void mapReduce() {
        // 为每个订单加上12%的税;因为只有一个参数,所以cost也可以不用括号;sum是自定义的一个变量
        double bill = intergerList02.stream().map(cost -> cost * 1.12).reduce((sum, cost) -> sum + cost).get();
        System.out.println("Total : " + bill);
    }

    private static void test01() {
        //转成其它数据结构比如set
        Set<Integer> integersSet = integerList.stream().collect(Collectors.toSet());
        //复合操作
        List<Integer> list = integerList.stream().filter(i -> i % 2 == 0).map(i -> i * i).distinct().collect(Collectors.toList());
    }

    /**
     * 排序并取出前n个元素
     * sorted(): It sorts the elements of stream using natural ordering. The element class must implement Comparable interface.
     * sorted(Comparator<? super T> comparator): Here we create an instance of Comparator using lambda expression. We can sort the stream elements in ascending and descending order.
     * To reverse the natural ordering Comparator provides reverseOrder() method. We use it as follows:list.stream().sorted(Comparator.reverseOrder())
     */
    private static void sortLimit() {
        // 取出前五个数据 [4, 5, 6, 1, 2]
        List<Integer> limitInteger = integerList.stream().limit(5).collect(Collectors.toList());
        //排序并且提取出前5个元素 [1,2,3,4,5]
        List<Integer> sortIntegers = integerList.stream().sorted().limit(5).collect(Collectors.toList());
        List<Integer> collect1 = integerList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        // 根据长度排行(初级版,不推荐)
        List<String> collect = strList.stream().sorted(Comparator.comparing(obj -> obj.length())).collect(Collectors.toList());
        // 根据长度排行,反转(初级版,不推荐)
        List<String> collect02 = strList.stream().sorted(Comparator.comparing(obj -> obj.length(), Comparator.reverseOrder())).collect(Collectors.toList());
        // 根据长度排行高级(初级版,不够装逼)
        List<String> collect03 = strList.stream().sorted(Comparator.comparing(String::length,Comparator.reverseOrder())).collect(Collectors.toList());
        // 根据长度排行高级另外(终极版本)
        List<String> collect04 = strList.stream().sorted(Comparator.comparing(String::length).reversed()).collect(Collectors.toList());
        // 根据用户名字字母顺序排名,反序(终极版本)
        List<User> collect2 = userList.stream().sorted(Comparator.comparing(User::getAge).thenComparing(User::getName).thenComparing(User::getPwd)).collect(Collectors.toList());
        System.out.println(collect2);
    }

    /**
     * 分组:groupingBy
     */
    private static void groupingBy() {
        //根据奇偶性分组:{false=[5, 1, 3, 7, 9], true=[4, 6, 2, 8, 8, 10]}
        Map<Boolean, List<Integer>> listMap = integerList.stream().collect(Collectors.groupingBy(i -> i % 2 == 0));
        System.out.println(listMap);
    }
}

class User{

    private String id;
    private String name;
    private String pwd;
    private Integer age;

)

 map新方法:

public class Test {

    static Map<String, String> map = new HashMap<>();
    static {
        map.put("11", "111");
        map.put("22", "222");
        map.put("33", "333");
    }

    public static void main(String[] args) {
        //        putNew();
    }

    private static void putNew() {

        // 如果 key 不存在或相关联的value值为 null, 则设置新的 key/value 值。
        map.putIfAbsent("11", "aaa");
        map.computeIfAbsent("11", k -> k + "22"); // 11 键已经存在了,所以对应的value值不被计算
        map.computeIfAbsent("55", k -> k + "22"); // 55 键还没有存在,所以计算,“55”+“22”
        // 如果key跟value都存在的话,则计算咯
        map.computeIfPresent("33", (k, v) -> k + v);
        // 只要 key 存在,不管对应值是否为  null,则用传入的 value 替代原来的值。即使传入的 value 是 null 也会用来替代原来的值,而不是删除
        map.replace("11", "bbb");
        // key 值存在且对应的value值,与第二个值相等时,用第三个值来替换新的value值
        map.replace("11", "bbb", "eee");
        // 对其中的key value值进行计算
        map.replaceAll((k,v) -> k + "-" + v);
        // 第一个值对应的value和第二个值相等的话,则移除
        map.remove("55","55-5522");
        /*
        computeIfAbsent 与 computeIfPresent  的结合体。也就是既不管 key 存不存在,也不管 key 对应的值是否为 null,
        compute 死活都要设置与 key 相关联的值,或者计算出的值为 null 时删除相应的 key, 返回值为最终的 map.get(key)。
         */
        String ret;
        Map<String, String> map01 = new HashMap<>() ;
        ret = map01.compute("a", (key, value) -> "a" + value); //ret="anull", map={"a":"anull"}
        ret = map01.compute("a", (key, value) -> "a" + value); //ret="aanull", map={"a":"aanull"}
        ret = map01.compute("a", (key, value) -> null); //ret=null, map={}
        System.out.println(map01);
    }

}

 

 时间操作

public class Test {

    public static void main(String[] args) {

        // 创建实例
        LocalDate now = LocalDate.now(); // 当前日期的localDate
        System.out.println(now); // 2019-09-16 尼玛,真的好屌
        LocalDateTime now1 = LocalDateTime.now();
        System.out.println(now1); // 2019-09-16T19:40:10.932 这个一般般
        LocalDate of = LocalDate.of(2012, 9, 16); // 年月日
        System.out.println(of); // 2012-09-16
        LocalTime now2 = LocalTime.now();
        System.out.println(now2); // 19:50:53.516
        YearMonth now3 = YearMonth.now();// 年月,例如信用卡到期

        // 重要的format和parse
        DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        DateTimeFormatter fmt1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = now.format(fmt);
        LocalDate parse = LocalDate.parse("2019-09-12", fmt);
        // 所以说啊,注意其中区别
        String format1 = now.format(DateTimeFormatter.BASIC_ISO_DATE); // 20190916
        String format2 = now.format(DateTimeFormatter.ISO_DATE); // 2019-09-16
        String format3 = now1.format(fmt1); // 注意格式要和LocalDateTime还是LocalDate对应
        System.out.println(format3); // 2019-09-16 19:40:10 好熟悉

        // 得到当前时间
        int year = now.getYear(); // 当前年份:2019
        Month month = now.getMonth(); // month 对象
        int value = month.getValue();// 当前月份:9
        int monthValue = now.getMonthValue(); // 当前月份:9
        int value1 = now.getDayOfWeek().getValue(); // 该日期是当前周的第几天:1
        int dayOfMonth = now.getDayOfMonth(); // 该日期是当前月的第几天:16
        int dayOfYear = now.getDayOfYear(); // 该日期是当前年的第几天:259
        int i = now.lengthOfYear(); // 返回当年有多少天:365
        int i1 = now.lengthOfMonth(); // 返回这个月有多少天:30

        // 修改
        LocalDate date = now.withYear(2020); // 修改该日期的年份,这样的话,date.getYear() 就是 2020 了
        LocalDate date1 = now.withMonth(6); // 修改该日期的月份

        // 判断
        boolean leapYear = now.isLeapYear(); // 判断是否是闰年:fasle
        boolean before = now.isBefore(parse); // 当前日期是否比它早
        boolean after = now.isAfter(parse); // 当前日期是否比它晚
        boolean equal = now.isEqual(parse); // 与当前日期是否一样
        boolean equals = now.equals(parse);
        // 只判断日月是否具相等
        MonthDay of1 = MonthDay.of(monthValue, dayOfMonth);
        MonthDay of2 = MonthDay.of(of.getMonthValue(), of.getDayOfMonth());
        System.out.println("of1.equals(of2)**" + of1.equals(of2) );

        // 添加、减少哦
        LocalDate date2 = now.plusDays(1);
        LocalDate date3 = now.plusWeeks(1);
        LocalDate date4 = now.plusMonths(1);
        LocalDate date5 = now.plusYears(1);
        LocalDate date6 = now.minusDays(1);
        LocalDate date7 = now.minusWeeks(1);
        LocalDate date8 = now.minusMonths(1);
        LocalDate date9 = now.minusYears(1);
        LocalDate plus = now.plus(1, ChronoUnit.WEEKS);// 一周后
        LocalDate plus1 = now.plus(1, ChronoUnit.MONTHS);// 一个月后
        System.out.println(now.plus(1, ChronoUnit.MONTHS).equals(now.plusMonths(1)) + "***********");

        // 相差多少时间, LocalDateTime 用 Duration
        String diao1 = "2019-09-12 23:23:23";
        String diao2 = "2019-09-16 23:24:23";
        // 为什么是后面减去前面,好奇怪,随便啦。不足四个小时就是四个小时,管尾巴是多少
        Duration between = Duration.between(LocalDateTime.parse(diao2,fmt1), LocalDateTime.parse(diao1,fmt1));
        long l = between.toDays();
        long l1 = between.toHours();
        System.out.println(l);
        System.out.println(l1);
        // LocalDate 用 Period
        String diao3 = "2019-09-12";
        Period between1 = Period.between(now, LocalDate.parse(diao3, DateTimeFormatter.ISO_DATE));
        System.out.println(between1.getDays());

    }

}

 asdfsafd

/**
     * 当前时间为2019年10月
     * @param args
     */
    public static void main(String[] args) {
        LocalDate date = LocalDate.now();
        // 创建一个新的日期,它的值为当月的第一天:2019-10-01
        LocalDate with = date.with(TemporalAdjusters.firstDayOfMonth());
        // 创建一个新的日期,它的值为当月的最后一天
        LocalDate with5 = date.with(TemporalAdjusters.lastDayOfMonth());
        // 创建一个新的日期,它的值为下月的第一天:2019-11-01
        LocalDate with1 = date.with(TemporalAdjusters.firstDayOfNextMonth());
        // 创建一个新的日期,它的值为当年的第一天
        LocalDate with2 = date.with(TemporalAdjusters.firstDayOfYear());
        // 创建一个新的日期,它的值为当年最后一天
        LocalDate with6 = date.with(TemporalAdjusters.lastDayOfYear());
        // 创建一个新的日期,它的值为明年的第一天
        LocalDate with3 = date.with(TemporalAdjusters.firstDayOfNextYear());
        // 创建一个新的日期,例如:当月的第一个星期一为7号
        LocalDate with4 = date.with(TemporalAdjusters.firstInMonth(DayOfWeek.MONDAY));
        // 创建一个新的日期,例如:当月的第一个星期一为28号
        LocalDate with7 = date.with(TemporalAdjusters.lastInMonth(DayOfWeek.MONDAY));
        // 创建一个新的日期,例如:当月的第二个星期一为14号
        LocalDate with8 = date.with(TemporalAdjusters.dayOfWeekInMonth(2, DayOfWeek.MONDAY));
        // 获取上月的最后一个星期一
        LocalDate with9 = date.with(TemporalAdjusters.dayOfWeekInMonth(0, DayOfWeek.MONDAY));
        // 获取这个月的倒数第一个星期一:28号
        LocalDate with10 = date.with(TemporalAdjusters.dayOfWeekInMonth(-1, DayOfWeek.MONDAY));
        // 获取下个星期五的日期
        LocalDate with11 = date.with(TemporalAdjusters.next(DayOfWeek.FRIDAY));
        System.out.println(with11);
    }

 

 

 

END

JDK8

原文:https://www.cnblogs.com/ericguoxiaofeng/p/11186367.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!