- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) > 編程語(yǔ)言 >
- Java8常用的新特性詳解
Lambda表達式:特殊的匿名內部類(lèi),語(yǔ)法更簡(jiǎn)潔。
Lanbda表達式允許把函數作為一個(gè)方法的參數(函數作為方法參數傳遞),將代碼像數據一樣傳遞。
基本語(yǔ)法:
<函數式接口> <變量名> = (參數1,參數2...) ->{ //方法體 }
Lambda引入了新的操作符:->(箭頭操作符),->將表達式分成兩部分
Lambda需要注意的事項:
語(yǔ)法格式一:
lambda 無(wú)參,無(wú)返回值
//如何使用lambda表達式 public class Demo1 { public static void main(String[] args) { //線(xiàn)程//匿名實(shí)現類(lèi)對象---以前的寫(xiě)法 // Runnable runnable=new Runnable() { // @Override // public void run() { // System.out.println("hello world!"); // } // }; //lambda表達式寫(xiě)法 Runnable runnable1= ()->System.out.println("hello world!"); new Thread(runnable1).start(); //更簡(jiǎn)單的寫(xiě)法 new Thread(()->System.out.println("hello world!")).start(); } }
語(yǔ)法格式二:
lambda 有一個(gè)參,無(wú)返回值
@Test public void test02(){ Consumer<String> con = new Consumer<String>() { @Override public void accept(String s){ System.out.println(s); } }; con.accept("hello world!"); System.out.println("*********************"); //Lambda表達式 Consumer<String> con1 = (String str)-> System.out.println(str); con1.accept("hello world"); }
語(yǔ)法格式三:
數據類(lèi)型可以省略,因為可由編譯器推斷得出,稱(chēng)為“類(lèi)型推斷”
@Test public void test03(){ Consumer<String> con1 = (str) -> System.out.println(str); con1.accept("hello world"); }
如果一個(gè)接口只有一個(gè)抽象方法,則該接口稱(chēng)之為函數式接口,函數式接口可以使用Lambda表達式,Lambda表達式會(huì )被匹配到這個(gè)抽象方法上。
@FunctionalInterface注解檢測接口是否符合函數式接口
public class Demo1 { public static void main(String[] args) { USB usb = new USB() { @Override public void show() { System.out.println("我是函數式接口"); } }; USB usb1=()-> System.out.println("你好"); info(()-> System.out.println("你好嘿嘿嘿")); } public static void info(USB usb){ usb.show(); } } //函數式接口 interface USB{ public void show(); }
lambda新增了四個(gè)重要的函數式接口:
函數式接口說(shuō)明
public class Demo2 { public static void main(String[] args) { // Consumer<Double> consumer=t-> System.out.println("吃飯消費掉:"+t); // Consumer<Double> consumer=new Consumer<Double>() { // @Override // public void accept(Double aDouble) { // System.out.println("你消費得金額:"+aDouble); // } // }; Consumer<Double> consumer1=t ->System.out.println("吃飯消費掉:"+t); Consumer<Double> consumer2=t ->System.out.println("唱歌消費掉:"+t); Consumer<Double> consumer3=t ->System.out.println("洗腳消費掉:"+t); hobby(consumer1,1000); hobby(consumer2,2000); hobby(consumer3,4000); Supplier<Integer> supplier=new Supplier<Integer>() { @Override public Integer get() { return new Random().nextInt(10); } }; Supplier<Integer> supplier1=()->new Random().nextInt(10); int[] arr = getArr(supplier1, 5); System.out.println(Arrays.toString(arr)); System.out.println("~~~~~~~~~~~~~~~function~~~~~~~~~~~~~~~~~~~~~~~"); // Function<String,String> function1=new Function<String, String>() { // @Override // public String apply(String s) { // return s.toUpperCase(); // } // }; // Function<String,String> function=s->s.toUpperCase(); // System.out.println(toUpper(function, "hello")); List<String> list=new ArrayList<>(); list.add("zhangsan"); list.add("lisi"); list.add("wangwu"); list.add("zhaoliu"); list.add("tianqi"); // Predicate<String> predicate=new Predicate<String>() { // @Override // public boolean test(String s) { // return s.length()>5; // } // }; Predicate<String> predicate1=s->s.length()>5; List<String> list1 = predicate(predicate1, list); System.out.println(list1); } //斷言型接口 返回true/false經(jīng)常用于判斷 public static List<String> predicate(Predicate<String> predicate,List<String> list){ List<String> newList=new ArrayList<>(); for(int i=0;i<list.size();i++){ if(predicate.test(list.get(i))){ newList.add(list.get(i)); } } return newList; } //函數型接口 有參數,且需要返回值 public static String toUpper(Function<String,String> function,String str){ return function.apply(str); } //消費性函數式接口 不需要返回值,有參數,經(jīng)常用于迭代 public static void hobby(Consumer<Double> consumer,double money){ consumer.accept(money); } //供給型函數式接口 無(wú)參數,指定返回值類(lèi)型,經(jīng)常用于只注重過(guò)程的代碼 public static int[] getArr(Supplier<Integer> supplier,int count){ int [] arr=new int[count]; for(int i=0;i<count;i++){ arr[i]=supplier.get(); } return arr; } }
方法引用式Lambda表達式的一種簡(jiǎn)寫(xiě)形式。如果Lambda表達式方法體中只是調用一個(gè)特定的已經(jīng)存在的方法,則可以使用方法引用。
常見(jiàn)的方法引用:
(1)構造器引用
**格式:**類(lèi)名::new
@Test public void test04(){ //普通寫(xiě)法 Supplier<Emp> supplier=new Supplier<Emp>() { @Override public Emp get() { return new Emp("劉德華"); } }; //類(lèi)名::new 方法引用 Supplier<Emp> supplier=Emp::new; //必須該類(lèi)中存在無(wú)參構造函數。 System.out.println(supplier.get()); } @Data @AllArgsConstructor @NoArgsConstructor class Emp{ private String name; }
(2)靜態(tài)方法引用
**格式:**類(lèi)名::靜態(tài)方法名
//類(lèi)::靜態(tài)方法 int compare(T o1, T o2); //Lambda表達式方法引用 Comparator<Integer> comparator=(o1,o2)->Integer.compare(o1,o2); //靜態(tài)方法引用Demo Comparator<Integer> comparator=Integer::compare; int compare = comparator.compare(18, 18); System.out.println(compare);
(3)類(lèi)的方法引用
**格式:**類(lèi)名::實(shí)例方法名
//lambda匿名方法引用 Function<Emp,String> function=e->{ return e.getName(); }; //類(lèi)名::實(shí)例方法 R apply(T t); Function<Emp,String> function=Emp::getName; System.out.println(function.apply(new Emp("劉德華")));
(4)實(shí)例對象的方法引用
**格式:**對象::實(shí)例方法名
//對象::實(shí)例方法 //這里System.out就是一個(gè)對象 Consumer<String> consumer2=System.out::println; consumer2.accept("你是劉德華嗎?");
流(Stream)中保存對集合或數組數據的操作。和集合類(lèi)似,但集合中保存的是數據。
特點(diǎn):
步驟:
創(chuàng )建一個(gè)流。
在一個(gè)或多個(gè)步驟中,將初始化Stream轉化到另一個(gè)Stream的中間操作。
使用一個(gè)終止操作來(lái)產(chǎn)生一個(gè)結果。該操作會(huì )強制它之前的延遲操作立即執行。在這之后,該Stream就不能使用了。
要注意的是,對流的操作完成后需要進(jìn)行關(guān)閉操作(或者用JAVA7的try-with-resources)。
獲取Stream對象的方式
public class Demo1 { public static void main(String[] args) { //1.通過(guò)Collection得對象中stream方法或parallelStream List<String> list=new ArrayList<>(); list.add("apple"); list.add("huawei"); list.add("xiaomi"); list.add("vivo"); Stream<String> stream = list.stream();//串行流 //遍歷集合(T t)-{}; 方法引用 stream.forEach(e->{ System.out.println(e); }); //方法引用 stream.forEach(System.out::println); Stream<String> stringStream = list.parallelStream(); //并行流 //2.通過(guò)Arrays轉化為流 int[] arr={2,34,5,6,7,2}; IntStream stream = Arrays.stream(arr); stream.forEach(System.out::println); //3.通過(guò)Stream中of,iterator,generator(); Stream<String> list = Stream.of("java01", "java02", "java03"); static <T> UnaryOperator<T> identity() { return t -> t; } UnaryOperator<Integer> unaryOperator=new UnaryOperator<Integer>() { @Override public Integer apply(Integer x) { return x+5; } }; UnaryOperator<Integer> unaryOperator=x->x+5; Stream<Integer> list = Stream.iterate(0,unaryOperator);//0,5,10,15,20,25,30 list.limit(10).forEach(System.out::println); Supplier<T> s Supplier<Integer> s=new Supplier() { @Override public Integer get() { return new Random().nextInt(50); } }; Supplier<Integer> s=()->new Random().nextInt(50); Stream<Integer> stream = Stream.generate(s); Stream<Integer> stream = Stream.generate(()->new Random().nextInt(50)); stream.limit(10).forEach(System.out::println); //IntStream LongStream DoubleStream IntStream stream = IntStream.rangeClosed(0, 90); stream.forEach(System.out::println); } }
中間操作.
filter、limit、skip、distinct、sorted map parallel
代碼操作
public class test02 { public static void main(String[] args) { //personList.stream()是創(chuàng )建流,filter()屬于中間操作,forEach、count()是終止操作。 List<Person> personList = new ArrayList<>(); personList.add(new Person("歐陽(yáng)雪",18,"中國",'F')); personList.add(new Person("Tom",24,"美國",'M')); personList.add(new Person("Tom",24,"美國",'M')); personList.add(new Person("Harley",22,"英國",'F')); personList.add(new Person("向天笑",20,"中國",'M')); personList.add(new Person("李康",22,"中國",'M')); personList.add(new Person("小梅",20,"中國",'F')); personList.add(new Person("何雪",21,"中國",'F')); personList.add(new Person("李康",22,"中國",'M')); //找出大于21歲的人 personList.stream().filter((person) -> person.getAge()>21).forEach(System.out::println); System.out.println("----------------------"); //查詢(xún)中國人有幾個(gè) long num = personList.stream().filter(p ->p.getCountry().equals("中國")).count(); System.out.println("中國人有:"+num+"個(gè)"); System.out.println("---------------------------"); //從Person列表中取出兩個(gè)女性。 personList.stream().filter((p) -> p.getSex() == 'F').limit(2).forEach(System.out::println); System.out.println("----------------------------"); //從Person列表中從第2個(gè)女性開(kāi)始,取出所有的女性。 personList.stream().filter((p) -> p.getSex() == 'F').skip(1).forEach(System.out::println); System.out.println("-------------------------------"); //去除掉了一個(gè)重復的數據 personList.stream().filter((p) -> p.getSex() == 'M').distinct().forEach(System.out::println); }
測試結果
在這個(gè)例子中,personList.stream()是創(chuàng )建流,filter()、limit()、skip()、distinct()屬于中間操作,forEach、count()是終止操作。
map舉例
例:比如,我們用一個(gè)PersonCountry類(lèi)來(lái)接收所有的國家信息:
System.out.println("**************************"); personList.stream().map((p) -> { Person personName = new Person(); personName.setCountry(p.getCountry()); return personName; }).distinct().forEach(System.out::println);
測試結果
自然排序比較好理解,這里只講一下定制排序,對前面的personList按年齡從小到大排序,年齡相同,則再按姓名排序:
final Stream<Person> sorted = personList.stream().sorted((p1, p2) -> { if (p1.getAge().equals(p2.getAge())) { return p1.getName().compareTo(p2.getName()); } else { return p1.getAge().compareTo(p2.getAge()); } }); sorted.forEach(System.out::println);
運行結果
forEach、min、max、count reduce、collect
allMatch
判斷personList中的人是否都是成年人:
final boolean adult = personList.stream().allMatch(p -> p.getAge() >= 18); System.out.println("是否都是成年人:" + adult); final boolean chinaese = personList.stream().allMatch(p -> p.getCountry().equals("中國")); System.out.println("是否都是中國人:" + chinaese);
運行結果
max min
判斷最大、最小的人信息
final Optional<Person> maxAge = personList.stream().max((p1, p2) -> p1.getAge().compareTo(p2.getAge())); System.out.println("年齡最大的人信息:" + maxAge.get()); final Optional<Person> minAge = personList.stream().min((p1, p2) -> p1.getAge().compareTo(p2.getAge())); System.out.println("年齡最小的人信息:" + minAge.get());
運行結果
求一個(gè)1到100的和
List<Integer> integerList = new ArrayList<>(100); for(int i = 1;i <= 100;i++) { integerList.add(i); } final Integer reduce = integerList.stream().reduce(0, (x, y) -> x + y); System.out.println("結果為:" + reduce);
運行結果
求所有人的年齡之和
final Optional<Integer> reduce = personList.stream().map(Person::getAge).reduce(Integer::sum); System.out.println("年齡總和:" + reduce);
年齡總和:193
改寫(xiě)map舉例中的的例子,將國家收集起來(lái)轉換成List
final List<String> collect = personList.stream().map(p -> p.getCountry()).distinct().collect(Collectors.toList()); System.out.println(collect);
輸出結果:[中國, 美國, 英國]
計算出平均年齡
final Double collect1 = personList.stream().collect(Collectors.averagingInt(p -> p.getAge())); System.out.println("平均年齡為:" + collect1);
平均年齡為:21.444444444444443
注意流的關(guān)閉
try(final Stream<Integer> integerStream = personList.stream().map(Person::getAge)) { final Optional<Integer> minAge = integerStream.collect(Collectors.minBy(Integer::compareTo)); System.out.println(minAge.get()); }
到此這篇關(guān)于Java8常用的新特性詳解的文章就介紹到這了,更多相關(guān)Java8常用的新特性?xún)热菡埶阉髂_本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自本網(wǎng)站內容采集于網(wǎng)絡(luò )互聯(lián)網(wǎng)轉載等其它媒體和分享為主,內容觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如侵犯了原作者的版權,請告知一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容,聯(lián)系我們QQ:712375056,同時(shí)歡迎投稿傳遞力量。
Copyright ? 2009-2022 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 特網(wǎng)科技 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 百度云 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站