目录

  • 常用API
    • Date类
    • SimpleDateFormat类
    • JDK8新日期类
      • LocalDate类
      • LocalTime类
      • LocalDateTime类
      • UpdateTime类
      • Instant类
      • DateTimeFormatter类
      • period类
      • Duration类
      • ChronoUnit类
    • Calendar类
  • 包装类
  • 正则表达式
  • Arrays类
    • 选择排序
    • 二分查找
  • Lambda表达式
    • 概述
    • 省略规则
    • 实例
  • JDK8新特性
    • 方法引用
    • 特定类型的方法引用
    • 构造器引用

常用API

Date类

package com.itheima.demo01api.date;import java.util.Date;/*** Date类:* 其对象代表当前所在系统的此刻时间* 常用方法:getTime(),获取时间毫秒值*/
public class Test {public static void main(String[] args) {//创建Date类对象Date d = new Date();//输出系统当前时间System.out.println(d);//获取时间对象的时间毫秒值long t = d.getTime();System.out.println(t);/*时间毫秒值转换为日期对象:方式一:使用Date类的有参构造器Date d = new Date(long l);*/long l = System.currentTimeMillis();System.out.println("当前时间毫秒值为:"+l);Date d1 = new Date(l);System.out.println("当前时间毫秒值对应的日期为:"+d1);/*方式二:Date类的setTime方法*/long l1 = System.currentTimeMillis();System.out.println("当前时间毫秒值为:"+l1);Date d2 = new Date();d2.setTime(l1);System.out.println("当前时间毫秒值对应的日期为:"+d2);/*案例:计算出当前时间往后走1小时121秒后的时间*/long l2 = System.currentTimeMillis();Date d3 = new Date();d3.setTime(l2);System.out.println("当前时间为:"+d3);l2 += (60*60+121)*1000;d3.setTime(l2);System.out.println("一小时121秒后的时间为"+d3);}
}

SimpleDateFormat类

Format()方法

package com.itheima.demo01api.simpledateformat;import java.text.SimpleDateFormat;
import java.util.Date;/*** SimpleDateFormat类* 作用:1.String Format(Object o)*          把Date类对象和时间毫秒值格式化为我们需要的格式*       2.Date parse(String s)可以将字符串解析为日期对象*/
public class Format {public static void main(String[] args) {Date d1 = new Date();//Sat Feb 18 12:16:06 GMT+08:00 2023System.out.println(d1);SimpleDateFormat sdf = new SimpleDateFormat();//格式化Date对象,使用的是默认格式String sd1 = sdf.format(d1);long time = d1.getTime();//格式化时间毫秒值,默认格式String t = sdf.format(time);//2023/2/18 下午12:16System.out.println(t);//2023/2/18 下午12:16System.out.println(sd1);//创建SimpleDateFormat对象,规定了格式化格式为:yyyy-MM-dd  aHH:mm:ss EEE//y表示年,M表示月,d表示日,H表示小时,m表示分,s表示秒,EEE表示星期几,a表示上下午SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd aHH:mm:ss EEE");long l = System.currentTimeMillis();System.out.println("当前时间毫秒值为:"+l);sdf1.format(l);System.out.println("以yyyy-MM-dd aHH:mm:ss EEE格式输出当前时间毫秒值:"+sdf1.format(l));}
}

parse()方法

package com.itheima.demo01api.simpledateformat;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;/*** 使用SimpleDateFormat类中的parse方法进行字符串解析* 案例:请计算出从2023年2月18日14点16分11秒,往后走2天14小时49分06秒后的时间*/
public class Parse {public static void main(String[] args) throws ParseException {String s = "2023年2月18日14点16分11秒";SimpleDateFormat sdf = new SimpleDateFormat("yyyy年M月dd日HH点mm分ss秒");Date d = sdf.parse(s);System.out.println("原时间为:" + s);long t = d.getTime();t += (2 * 24 * 60 * 60 + 14 * 60 * 60 + 49 * 60 + 6) * 1000;d.setTime(t);System.out.println("往后走2天14小时49分06秒后的时间为:" + sdf.format(d));}
}

案例:

package com.itheima.demo01api.simpledateformat;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;/*** 案例:秒杀活动* 需求:秒杀开始时间:2020年11月11日 00:00:00,持续十分钟* 小贾下单时间:2020年11月11日 00:03:47* 小皮下单时间:2020年11月11日 00:10:11* 请判断小贾和小皮是否秒杀成功*/
public class Case {public static void main(String[] args) throws ParseException {String startTime = "2020年11月11日 00:00:00";String endsTime = "2020年11月11日 00:10:00";String xiaoJia = "2020年11月11日 00:03:47";String xiaoPi = "2020年11月11日 00:10:11";SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");Date st = sdf.parse(startTime);Date et = sdf.parse(endsTime);Date xj = sdf.parse(xiaoJia);Date xp = sdf.parse(xiaoPi);if (xj.before(et) && xj.after(st)){System.out.println("小贾秒杀成功,开始发货");}else{System.out.println("小贾秒杀失败");}if (xp.before(et) && xp.after(st)){System.out.println("小皮秒杀成功,开始发货");}else{System.out.println("小皮秒杀失败");}}
}

JDK8新日期类

LocalDate类

package com.itheima.demo01api.jdk8time;import java.time.LocalDate;
import java.time.Month;public class Demo01LocalDate {public static void main(String[] args) {// 1、获取本地日期对象。LocalDate nowDate = LocalDate.now();System.out.println("今天的日期:" + nowDate);//今天的日期:int year = nowDate.getYear();System.out.println("year:" + year);int month = nowDate.getMonthValue();System.out.println("month:" + month);int day = nowDate.getDayOfMonth();System.out.println("day:" + day);//当年的第几天int dayOfYear = nowDate.getDayOfYear();System.out.println("dayOfYear:" + dayOfYear);//星期System.out.println(nowDate.getDayOfWeek());System.out.println(nowDate.getDayOfWeek().getValue());//月份System.out.println(nowDate.getMonth());//AUGUSTSystem.out.println(nowDate.getMonth().getValue());//8System.out.println("------------------------");LocalDate bt = LocalDate.of(1991, 11, 11);System.out.println(bt);//直接传入对应的年月日System.out.println(LocalDate.of(1991, Month.NOVEMBER, 11));//相对上面只是把月换成了枚举}
}

LocalTime类

 package com.itheima.demo01api.jdk8time;import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;public class Demo02LocalTime {public static void main(String[] args) {// 1、获取本地时间对象。LocalTime nowTime = LocalTime.now();System.out.println("今天的时间:" + nowTime);//今天的时间:int hour = nowTime.getHour();//时System.out.println("hour:" + hour);//hour:int minute = nowTime.getMinute();//分System.out.println("minute:" + minute);//minute:int second = nowTime.getSecond();//秒System.out.println("second:" + second);//second:int nano = nowTime.getNano();//纳秒System.out.println("nano:" + nano);//nano:System.out.println("-----");System.out.println(LocalTime.of(8, 20));//时分System.out.println(LocalTime.of(8, 20, 30));//时分秒System.out.println(LocalTime.of(8, 20, 30, 150));//时分秒纳秒LocalTime mTime = LocalTime.of(8, 20, 30, 150);System.out.println("---------------");System.out.println(LocalDateTime.of(1991, 11, 11, 8, 20));System.out.println(LocalDateTime.of(1991, Month.NOVEMBER, 11, 8, 20));System.out.println(LocalDateTime.of(1991, 11, 11, 8, 20, 30));System.out.println(LocalDateTime.of(1991, Month.NOVEMBER, 11, 8, 20, 30));System.out.println(LocalDateTime.of(1991, 11, 11, 8, 20, 30, 150));System.out.println(LocalDateTime.of(1991, Month.NOVEMBER, 11, 8, 20, 30, 150));}
}

LocalDateTime类

package com.itheima.demo01api.jdk8time;import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;public class Demo03LocalDateTime {public static void main(String[] args) {// 日期 时间LocalDateTime nowDateTime = LocalDateTime.now();System.out.println("今天是:" + nowDateTime);//今天是:System.out.println(nowDateTime.getYear());//年System.out.println(nowDateTime.getMonthValue());//月System.out.println(nowDateTime.getDayOfMonth());//日System.out.println(nowDateTime.getHour());//时System.out.println(nowDateTime.getMinute());//分System.out.println(nowDateTime.getSecond());//秒System.out.println(nowDateTime.getNano());//纳秒//日:当年的第几天System.out.println("dayOfYear:" + nowDateTime.getDayOfYear());//dayOfYear:249//星期System.out.println(nowDateTime.getDayOfWeek());//THURSDAYSystem.out.println(nowDateTime.getDayOfWeek().getValue());//4//月份System.out.println(nowDateTime.getMonth());//SEPTEMBERSystem.out.println(nowDateTime.getMonth().getValue());//9LocalDate ld = nowDateTime.toLocalDate();System.out.println(ld);LocalTime lt = nowDateTime.toLocalTime();System.out.println(lt.getHour());System.out.println(lt.getMinute());System.out.println(lt.getSecond());}
}

UpdateTime类

package com.itheima.demo01api.jdk8time;import java.time.LocalDate;
import java.time.LocalTime;
import java.time.MonthDay;public class Demo04UpdateTime {public static void main(String[] args) {LocalTime nowTime = LocalTime.now();System.out.println(nowTime);//当前时间System.out.println(nowTime.minusHours(1));//一小时前System.out.println(nowTime.minusMinutes(1));//一分钟前System.out.println(nowTime.minusSeconds(1));//一秒前System.out.println(nowTime.minusNanos(1));//一纳秒前System.out.println("----------------");System.out.println(nowTime.plusHours(1));//一小时后System.out.println(nowTime.plusMinutes(1));//一分钟后System.out.println(nowTime.plusSeconds(1));//一秒后System.out.println(nowTime.plusNanos(1));//一纳秒后System.out.println("------------------");// 不可变对象,每次修改产生新对象!System.out.println(nowTime);System.out.println("---------------");LocalDate myDate = LocalDate.of(2018, 9, 5);LocalDate nowDate = LocalDate.now();System.out.println("今天是2018-09-06吗? " + nowDate.equals(myDate));//今天是2018-09-06吗? falseSystem.out.println(myDate + "是否在" + nowDate + "之前? " + myDate.isBefore(nowDate));//2018-09-05是否在2018-09-06之前? trueSystem.out.println(myDate + "是否在" + nowDate + "之后? " + myDate.isAfter(nowDate));//2018-09-05是否在2018-09-06之后? falseSystem.out.println("---------------------------");// 判断今天是否是你的生日LocalDate birDate = LocalDate.of(1996, 8, 5);LocalDate nowDate1 = LocalDate.now();MonthDay birMd = MonthDay.of(birDate.getMonthValue(), birDate.getDayOfMonth());MonthDay nowMd = MonthDay.from(nowDate1);System.out.println("今天是你的生日吗? " + birMd.equals(nowMd));//今天是你的生日吗? false}
}

Instant类

package com.itheima.demo01api.jdk8time;import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;public class Demo05Instant {public static void main(String[] args) {// 1、得到一个Instant时间戳对象Instant instant = Instant.now();System.out.println(instant);// 2、系统此刻的时间戳怎么办?Instant instant1 = Instant.now();System.out.println(instant1.atZone(ZoneId.systemDefault()));// 3、如何去返回Date对象Date date = Date.from(instant);System.out.println(date);Instant i2 = date.toInstant();System.out.println(i2);}
}

DateTimeFormatter类

package com.itheima.demo01api.jdk8time;import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class Demo06DateTimeFormat {public static void main(String[] args) {// 本地此刻  日期时间 对象LocalDateTime ldt = LocalDateTime.now();System.out.println(ldt);// 解析/格式化器DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss EEE a");// 正向格式化System.out.println(dtf.format(ldt));// 逆向格式化System.out.println(ldt.format(dtf));// 解析字符串时间DateTimeFormatter dtf1 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");// 解析当前字符串时间成为本地日期时间对象LocalDateTime ldt1 = LocalDateTime.parse("2019-11-11 11:11:11" ,  dtf1);System.out.println(ldt1);System.out.println(ldt1.getDayOfYear());}
}

period类

package com.itheima.demo01api.jdk8time;import java.time.LocalDate;
import java.time.Period;public class Demo07Period {public static void main(String[] args) {// 当前本地 年月日LocalDate today = LocalDate.now();System.out.println(today);// 生日的 年月日LocalDate birthDate = LocalDate.of(1998, 10, 13);System.out.println(birthDate);Period period = Period.between(birthDate, today);//第二个参数减第一个参数System.out.println(period.getYears());System.out.println(period.getMonths());System.out.println(period.getDays());}
}

Duration类

package com.itheima.demo01api.jdk8time;import java.time.Duration;
import java.time.LocalDateTime;public class Demo08Duration {public static void main(String[] args) {// 本地日期时间对象。LocalDateTime today = LocalDateTime.now();System.out.println(today);// 出生的日期时间对象LocalDateTime birthDate = LocalDateTime.of(2021,8,06,01,00,00);System.out.println(birthDate);Duration duration = Duration.between(  today , birthDate);//第二个参数减第一个参数System.out.println(duration.toDays());//两个时间差的天数System.out.println(duration.toHours());//两个时间差的小时数System.out.println(duration.toMinutes());//两个时间差的分钟数System.out.println(duration.toMillis());//两个时间差的毫秒数System.out.println(duration.toNanos());//两个时间差的纳秒数}
}

ChronoUnit类

package com.itheima.demo01api.jdk8time;import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;public class Demo09ChronoUnit {public static void main(String[] args) {// 本地日期时间对象:此刻的LocalDateTime today = LocalDateTime.now();System.out.println(today);// 生日时间LocalDateTime birthDate = LocalDateTime.of(1990,10,1,10,50,59);System.out.println(birthDate);System.out.println("相差的年数:" + ChronoUnit.YEARS.between(birthDate, today));System.out.println("相差的月数:" + ChronoUnit.MONTHS.between(birthDate, today));System.out.println("相差的周数:" + ChronoUnit.WEEKS.between(birthDate, today));System.out.println("相差的天数:" + ChronoUnit.DAYS.between(birthDate, today));System.out.println("相差的时数:" + ChronoUnit.HOURS.between(birthDate, today));System.out.println("相差的分数:" + ChronoUnit.MINUTES.between(birthDate, today));System.out.println("相差的秒数:" + ChronoUnit.SECONDS.between(birthDate, today));System.out.println("相差的毫秒数:" + ChronoUnit.MILLIS.between(birthDate, today));System.out.println("相差的微秒数:" + ChronoUnit.MICROS.between(birthDate, today));System.out.println("相差的纳秒数:" + ChronoUnit.NANOS.between(birthDate, today));System.out.println("相差的半天数:" + ChronoUnit.HALF_DAYS.between(birthDate, today));System.out.println("相差的十年数:" + ChronoUnit.DECADES.between(birthDate, today));System.out.println("相差的世纪(百年)数:" + ChronoUnit.CENTURIES.between(birthDate, today));System.out.println("相差的千年数:" + ChronoUnit.MILLENNIA.between(birthDate, today));System.out.println("相差的纪元数:" + ChronoUnit.ERAS.between(birthDate, today));}
}

Calendar类

package com.itheima.demo01api.calendar;import java.util.Calendar;
import java.util.Date;/*** Calendar是一个抽象类,创建不了对象* Calendar对象代表当前系统此刻时间的日历对象* Calendar的方法:* 1.static Calendar getInstance();返回一个日历对象* 2.int get(int field);取日历中的某个字段信息* 3.void set(int field,int value);修改日历的某个字段* 4.void add(int field,int amount);为某个字段增加/减少指定的值* 5.final Date getTime();获取此刻日期对象* 6.long getTimeInMillis();获取此刻时间毫秒值*/
public class Test {public static void main(String[] args) {//通过getInstance方法获取Calendar对象Calendar ins = Calendar.getInstance();//输出日历里的信息(一大串)System.out.println(ins);//int get(int field);取日历中的某个字段信息,MONTH从0开始计数,所以要加一int month = ins.get(Calendar.MONTH)+1;System.out.println(month);//void set(int field,int value);修改日历的某个字段//将月份改为4,静态成员直接使用类名调用//ins.set(Calendar.MONTH,4);//void add(int field,int amount);为某个字段增加/减少指定的值ins.add(Calendar.MONTH,-1);System.out.println(ins);//final Date getTime();获取此刻日期对象Date time = ins.getTime();System.out.println(time);//64天10小时后是什么时间Date tt = ins.getTime();System.out.println(tt);ins.add(Calendar.DAY_OF_YEAR,64);ins.add(Calendar.HOUR,10);Date t = ins.getTime();System.out.println(t);//long getTimeInMillis();获取此刻时间毫秒值System.out.println(ins.getTimeInMillis());}
}

包装类

package com.itheima.demo02integer;/*** 包装类:* 八种基本数据类型的引用数据类型* 后面集合和泛型也只支持引用数据类型* 基本数据类型和其引用数据类型可以相互直接赋值,称为自动装箱、自动拆箱* 特有功能:* 包装类默认值可以是null,容错率跟高* 可以把基本数据类型转换成字符串类型(用处不大)* 可以把字符串的数值转换成真实数据类型(大大滴有用)*/
public class Test {public static void main(String[] args) {//自动装箱int a = 10;Integer b = a;//10System.out.println(b);//自动拆箱Integer c = 4;a = c;//4System.out.println(a);Integer d = null;
//        int x = null;报错//nullSystem.out.println(d);//1.把基本数据类型转换成字符串类型Integer i = 11;String si = i.toString();//111System.out.println(si+1);//不如直接加""Integer i1 = 20;String s1 = i1 + "";//201System.out.println(s1+1);//2.把字符串的数值转换成真实数据类型String ss = "2354";//字符串里必须是整数,不能有别的,否则报NumberFormatException//int i2 = Integer.parseInt(ss);//不如使用valueOf方法int i2 = Integer.valueOf(ss);//2354System.out.println(i2);String s3 = "23.55";//字符串里必须是小数,不能有别的,否则报NumberFormatException//double v = Double.parseDouble(s3);//不如使用valueOf方法Double v = Double.valueOf(s3);//23.55System.out.println(v);}
}

正则表达式

package com.itheima.demo03regex;import java.util.Scanner;/*** 需求:* 校验qq号码,必须全部数字,6-20位*/
public class Demo01Regex {public static void main(String[] args) {checkQQ();}private static void checkQQ() {System.out.println("请输入QQ号:");Scanner s = new Scanner(System.in);String qq = s.next();if (qq.matches("\\d{6,20}")){System.out.println("输入正确");}else{System.out.println("格式错误");}}
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5qZR5iDy-1677463850448)(H:\JavaLearning\document\笔记\img\正则表达式匹配规则.png)]

package com.itheima.demo03regex;/**目标:全面、深入学习正则表达式的规则*/
public class Demo02Regex {public static void main(String[] args) {//public boolean matches(String regex):判断是否与正则表达式匹配,匹配返回true// 只能是 a  b  cSystem.out.println("a".matches("[abc]")); // trueSystem.out.println("z".matches("[abc]")); // false// 不能出现a  b  cSystem.out.println("a".matches("[^abc]")); // falseSystem.out.println("z".matches("[^abc]")); // trueSystem.out.println("a".matches("\\d")); // falseSystem.out.println("3".matches("\\d")); // trueSystem.out.println("333".matches("\\d")); // falseSystem.out.println("z".matches("\\w")); // trueSystem.out.println("2".matches("\\w")); // trueSystem.out.println("21".matches("\\w")); // falseSystem.out.println("你".matches("\\w")); //falseSystem.out.println("你".matches("\\W")); // trueSystem.out.println("---------------------------------");//  以上正则匹配只能校验单个字符。// 校验密码// 必须是数字 字母 下划线 至少 6位System.out.println("2442fsfsf".matches("\\w{6,}"));System.out.println("244f".matches("\\w{6,}"));// 验证码 必须是数字和字符  必须是4位System.out.println("23dF".matches("[a-zA-Z0-9]{4}"));System.out.println("23_F".matches("[a-zA-Z0-9]{4}"));System.out.println("23dF".matches("[\\w&&[^_]]{4}"));System.out.println("23_F".matches("[\\w&&[^_]]{4}"));}
}
package com.itheima.demo03regex;import java.util.Scanner;/*** 校验手机号码、邮箱、座机号码*/
public class Demo03Regex {public static void main(String[] args) {checkPhoneNumber();checkEmail();checkTelNumber();}private static void checkTelNumber() {while (true) {System.out.println("请输入座机号码:");Scanner s = new Scanner(System.in);String s1 = s.next();if (s1.matches("0\\d{2,6}-?\\d{5,20}")) {System.out.println("输入正确");break;}else{System.out.println("格式错误");}}}private static void checkEmail() {while (true) {System.out.println("请输入邮箱:");Scanner s = new Scanner(System.in);String s1 = s.next();if (s1.matches("\\w{1,30}@[a-zA-Z0-9]{2,20}(\\.[a-zA-Z0-9]{2,20}){1,2}")) {System.out.println("输入正确");break;}else{System.out.println("格式错误");}}}private static void checkPhoneNumber() {while (true) {System.out.println("请输入手机号:");Scanner s = new Scanner(System.in);String s1 = s.next();if (s1.matches("1[3,9]\\d{9}")) {System.out.println("输入正确");break;}else{System.out.println("格式错误");}}}}
package com.itheima.demo03regex;import java.util.Arrays;/*** 正则表达式在字符串方法中的应用* split()方法、replaceAll()方法*/
public class Demo04Regex {public static void main(String[] args) {String s = "小米sgasa4e3华为ga三星";//使用split方法切割字符串String[] s1 = s.split("\\w+");//[小米, 华为, 三星]System.out.println(Arrays.toString(s1));//使用replaceAll方法替换字符串String s2 = s.replaceAll("\\w+", "\t");//小米   华为  三星System.out.println(s2);}
}
package com.itheima.demo03regex;import java.util.regex.Matcher;
import java.util.regex.Pattern;/*** 使用正则表达式爬取信息内容*/
public class Demo05Regex {public static void main(String[] args) {String rs = "来黑马程序学习Java,电话020-43422424,或者联系邮箱" +"itcast@itcast.cn,电话18762832633,0203232323" +"邮箱bozai@itcast.cn,400-100-3233 ,4001003232";//将匹配规则编译成匹配对象Pattern c = Pattern.compile("(0\\d{2,6}-?\\d{5,20})" +"|(\\w{1,30}@[a-zA-Z0-9]{2,20}(\\.[a-zA-Z0-9]{2,20}){1,2})" +"|(1[3-9]\\d{9})|(400-?\\d{3,4}-?\\d{3,4})");//得到内容匹配器对象Matcher matcher = c.matcher(rs);//输出while (matcher.find()){System.out.println(matcher.group());}}
}

Arrays类

package com.itheima.demo04arrays;import java.util.Arrays;
import java.util.Comparator;/*** Arrays类:数组操作工具栏* Arrays类的常见API:* 1.String toString(类型[] a),将数组转换成字符串* 2.void sort(类型[] a),对数组默认进行升序排序* 3.void sort(类型[] a,Comparator<?super T>c),使用比较器对象自定义排序* 4.int binarySearch(int[] a,int key),二分查找数组元素,找到返回索引,否则返回-1*/
public class Demo01Api {public static void main(String[] args) {int[] arr = {23,45,16,89,20};//使用toString方法打印输出arr数组元素System.out.println(Arrays.toString(arr));//使用sort方法对数组arr升序排序Arrays.sort(arr);System.out.println(Arrays.toString(arr));//使用sort方法对数组arr自定义排序,只支持引用数据类型//需求:降序排序Integer[] arr1 = new Integer[arr.length];for (int i = 0; i < arr.length; i++) {Integer temp = arr[i];arr1[i] = temp;}
//        Arrays.sort(arr1, new Comparator<Integer>() {//            @Override
//            public int compare(Integer o1, Integer o2) {//                //如果返回的是正数,表示要交换两个数的位置,负数不交换,0表示相等
//                return o2-o1;
//            }
//        });//使用Lambda表达式简化后Arrays.sort(arr1, ( o1, o2)-> {//如果返回的是正数,表示要交换两个数的位置,负数不交换,0表示相等return o2-o1; });System.out.println(Arrays.toString(arr1));//二分查找,返回索引或-1int index = Arrays.binarySearch(arr, 45);System.out.println(index);}
}

选择排序

package com.itheima.demo04arrays;import java.util.Arrays;/*** 选择排序*/
public class Demo02SelectiveSort {public static void main(String[] args) {int[] ints = {1,7,5,3,6,4,8};System.out.println(Arrays.toString(ints));SelectiveSort(ints);System.out.println(Arrays.toString(ints));}/*** 选择排序,升序* @param ints 需要排序的数组*/private static void SelectiveSort(int[] ints) {for (int i = 0; i < ints.length-1; i++) {for (int j = i+1; j < ints.length; j++) {//将较大值交换到后面if (ints[i]>ints[j]){ints[i] = ints[i]^ints[j];ints[j] = ints[i]^ints[j];ints[i] = ints[i]^ints[j];}}}}
}

二分查找

package com.itheima.demo04arrays;import java.util.Arrays;/*** 二分查找*/
public class Demo03BinarySearch {public static void main(String[] args) {int[] arr = {1,7,5,3,6,4,8};System.out.println(Arrays.toString(arr));Arrays.sort(arr);System.out.println(Arrays.toString(arr));int index = binaryFind(arr, 7,0,arr.length-1);System.out.println(index);}private static int binaryFind(int[] arr, int key,int min,int max) {while (min<=max){int index = (max +min)/2;if (arr[index]>key){max = index -1;}else if (arr[index]<key){min = index +1;}else {return index;}}return -1;}
}

Lambda表达式

概述

package com.itheima.demo05lambda;/*** Lambda表达式概述* JDK8开始以后的新语法* 作用:简化匿名内部类代码写法* 简化格式:(匿名内部类被重写方法的参数列表)->{*     被重写方法的方法体代码* }* 注:->是语法形式,无实际含义* 注意:Lambda表达式只能简写函数式接口的匿名内部类写法形式* 函数式接口:有且仅有一个抽象方法的接口*/
public class Demo01labmda {public static void main(String[] args) {//        USB Mouse = new USB() {//            @Override
//            public void connect() {//                System.out.println("鼠标已连接");
//            }
//        };
//        test(Mouse);//使用lambda标准格式简化匿名内部类的代码形式USB Mouse = ()->{ System.out.println("鼠标已连接"); };test(Mouse);System.out.println("=========================================");//进一步简化test(()->{System.out.println("鼠标已连接");});//再次简化test(()-> System.out.println("鼠标已连接"));}public static void test(USB usb){usb.connect();}
}
@FunctionalInterface//加上此注解就必须是函数式接口,只能有一个抽象方法
interface USB{void connect();
}

省略规则

实例

package com.itheima.demo05lambda;import javax.swing.*;
import java.awt.event.ActionEvent;
import java.util.Arrays;/*** Lambda实例*/
public class Demo02lambda {public static void main(String[] args) {//简化Comparator接口匿名形式Integer[] arr= {1,7,0,4,6};
//        Arrays.sort(arr, new Comparator<Integer>() {//            @Override
//            public int compare(Integer o1, Integer o2) {//                return o2-o1;
//            }
//        });//简化后Arrays.sort(arr, (Integer o1,Integer  o2)-> {return o2-o1;});//再次简化Arrays.sort(arr, (o1,o2)-> o2-o1);//简化按钮监听器ActionListener的匿名形式JFrame jFrame = new JFrame("登录窗口");jFrame.setSize(300,300);jFrame.setVisible(true);JButton btn = new JButton("登录");jFrame.add(btn);
//        btn.addActionListener(new ActionListener() {//            @Override
//            public void actionPerformed(ActionEvent e) {//                System.out.println("点击成功");
//            }
//        });//简化后btn.addActionListener((ActionEvent e) ->{System.out.println("点击成功");});//再次简化btn.addActionListener(e -> System.out.println("点击成功"));}
}

JDK8新特性

方法引用

package com.itheima.jdk8newcharacteristic;import com.itheima.jdk8newcharacteristic.domain.CompareStudent;
import com.itheima.jdk8newcharacteristic.domain.Student;import java.util.ArrayList;
import java.util.Arrays;public class Test {public static void main(String[] args) {Student[] students = new Student[4];students[0] = new Student("蜘蛛精", 169.5, 23);students[1] = new Student("紫霞", 163.8, 26);students[2] = new Student("紫霞", 163.0, 26);students[3] = new Student("至尊宝", 167.5, 24);//静态方法引用,使用类名调用Arrays.sort(students, CompareStudent::compareByAge);CompareStudent c = new CompareStudent();//实例方法引用使用对象调用Arrays.sort(students,c::compareByHeight);ArrayList<String> list = new ArrayList<>();list.add("蜘蛛精");list.add("孙悟空");list.add("紫霞");list.add("至尊宝");//构造器引用String[] name = list.stream().toArray(String[]::new);}
}

CompareStudent类

package com.itheima.jdk8newcharacteristic.domain;public class CompareStudent {public static int compareByAge(Student o1, Student o2){return o1.getAge()-o2.getAge();}public  int compareByHeight(Student o1, Student o2){return Double.compare(o1.getHeight(),o2.getHeight());}}

Student类

package com.itheima.jdk8newcharacteristic.domain;public class Student {private String name;private double height;private int age;public String getName() {return name;}public void setName(String name) {this.name = name;}public double getHeight() {return height;}public void setHeight(double height) {this.height = height;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public Student(String name, double height, int age) {this.name = name;this.height = height;this.age = age;}public Student() {}
}

特定类型的方法引用

package com.itheima.jdk8newcharacteristic;import java.util.Arrays;
import java.util.Comparator;/*** Java约定:*     如果某个Lambda表达式里只是调用一个实例方法,*     并且前面参数列表中的第一个参数作为方法的主调,*     后面的所有参数都是作为该实例方法的入参时,则就可以使用特定类型的方法引用。* 格式:*    类型::方法名*/
public class Test2 {public static void main(String[] args) {String[] names = {"boby", "angela", "Andy" ,"dlei", "caocao", "Babo", "jack", "Cici"};// 要求忽略首字符大小写进行排序。Arrays.sort(names, new Comparator<String>() {@Overridepublic int compare(String o1, String o2) {// 制定比较规则。o1 = "Andy"  o2 = "angela"return o1.compareToIgnoreCase(o2);}});//lambda表达式写法Arrays.sort(names, ( o1,  o2) -> o1.compareToIgnoreCase(o2) );//特定类型的方法引用!Arrays.sort(names, String::compareToIgnoreCase);System.out.println(Arrays.toString(names));}
}

构造器引用

package com.itheima.jdk8newcharacteristic;import com.itheima.jdk8newcharacteristic.domain.Car;
import com.itheima.jdk8newcharacteristic.domain.CreateCar;public class Test3 {public static void main(String[] args) {// 1、创建这个接口的匿名内部类对象。CreateCar cc1 = new CreateCar(){@Overridepublic Car create(String name, double price) {return new Car(name, price);}};//2、使用匿名内部类改进CreateCar cc2 = (name, price) -> new Car(name, price);//3、使用方法引用改进:构造器引用CreateCar cc3 = Car::new;//注意:以上是创建CreateCar接口实现类对象的几种形式而已,语法一步一步简化。//4、对象调用方法Car car = cc3.create("奔驰", 49.9);System.out.println(car);}
}

Car类

package com.itheima.jdk8newcharacteristic.domain;public class Car {private String name;private double price;public Car() {}public Car(String name, double price) {this.name = name;this.price = price;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}@Overridepublic String toString() {return "Car{" +"name='" + name + '\'' +", price=" + price +'}';}
}

CreateCar类

package com.itheima.jdk8newcharacteristic.domain;public interface CreateCar {Car create(String name, double price);}

day21-java(改)相关推荐

  1. copy所有的java文件到硬盘_将d:\java目录下的所有.java文件复制到d:\jad目录下,并将原来文件的扩展名从.java改为.jad...

    listFiles方法接受一个FileFilter对象,这个FileFilter对象就是过虑的策略对象,不同的人提供不同的FileFilter实现,即提供了不同的过滤策略. //将d:\java目录下 ...

  2. 将d:\java目录下的所有.java文件复制到d:\jad 目录下,并将原来文件的扩展名从.java 改为.jad

    package com;import java.io.*; import java.util.ArrayList; import java.util.List; /* 编写一个程序,将d:\java目 ...

  3. 编写一个程序,将d:\java目录下的所有.java文件复制到d:\jad目录下,并将原来文件的扩展名从.java改为.jad

    package com.hbut.test; import java.io.File; import java.io.FileNotFoundException; import java.io.Fil ...

  4. Java算法面试题:编写一个程序,将e:\neck目录下的所有.java文件复制到e:\jpg目录下,并将原来文件的扩展名从.java改为.jpg...

    package com.swift;import java.io.File; import java.io.FileFilter; import java.io.FileInputStream; im ...

  5. Java改知能机_Java 面试突击之 Java 并发知识基础 进阶考点全解析

    版权说明:本文内容根据 github 开源项目整理所得 项目地址:https://github.com/Snailclimb/JavaGuide​github.com 一.基础 什么是线程和进程? 何 ...

  6. java改成字体_更改JRE字体配置

    (1) JRE 1.4 的字体配置文件以及配置语法 关于 JRE1.4 的字体配置方法可参考 Sun 网站上的专门介绍: http://java.sun.com/j2se/1.4.2/docs/gui ...

  7. java改文字乱码快捷键,java.util.Properties读取中文内容(UTF-8格式)的配置文件,发生中文乱码...

    转自 http://blog.csdn.net/zhangzikui/article/details/7708827 碰到了用java.util.Properties读取中文内容(UTF-8格式)的配 ...

  8. java 改为matlab_用面向对象的方法将一段JAVA代码转化为matlab

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 public class Variable { /*list of variables this variable is connected to. */ ...

  9. 编写一个程序,将 d:\java 目录下的所有.java 文件复制到 d:\jad 目录下,并将原来文件的扩展名从.java 改为.jad。...

    package IO; import java.io.*; public class FileCopy {public static void main(String[] args) throws E ...

  10. java改图软件,【图片】【转载】【新手必看】各种改软必备软件使用方法【playjava吧】_百度贴吧...

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 前几天改软找不到这些软件和使用方法,所以就上网搜了这些,给不会用的友友分享下-小爽也在此祝大家新年快乐! [MC] 也叫minicommander,是手机 ...

最新文章

  1. 能源结构进入变革时代 光伏业趋于壮大转型
  2. JZOJ 1251. 收费站
  3. 转:SCI、EI和ISTP收录号的查询方法
  4. vi编辑器基本使用方法
  5. html5 自定义属性data-*
  6. css不常用,不常用的 CSS
  7. php declare 作用,php declare用法详解
  8. 如何解决Mybatis里mapper文件中关于不能用大于小于号
  9. mysql去掉小数点多余0_mysql数据库个性化需求:版本号排序
  10. python使用virtualenvwrapper
  11. UIActionSheet的最后一项点击失效
  12. 6、ES6的let和const
  13. wxpython wx listctrl_wxPython实现指定单元格可编辑的ListCtrl | 学步园
  14. 排查DHCP服务器故障
  15. MATLAB机械动力分析,基于MATLAB的柔性机械臂动力学分析
  16. 管理大师德鲁克60句经典名言
  17. Tether聘请前银行分析师首席合规官
  18. CORDIC算法详解(一)- CORDIC 算法之圆周系统之旋转模式( Rotation Mode )
  19. 制作镜像实例之healthcheck
  20. tensor.view()函数--自己的理解《pytorch学习》

热门文章

  1. 码农必备?清华大学开源了一款写代码神器。。。
  2. Hyperspectral imagery dataset
  3. Windows11万用更新教程(跳过系统检测)(W002)
  4. ZOJ 2302 Elevator
  5. tkinter的容器组件Frame讲解
  6. 【语音识别学习】科大讯飞APPID的申请以及SDK下载
  7. 营销号废话生成器-python
  8. 基于HTML5的移动阅读器
  9. arcgis怎么关联excel表_在arcgis中添加excel表格数据-ArcGIS如何将Excel里的数据关联至地图上...
  10. android百度播放器,终结媒体播放器 百度推新Android浏览器