溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

java8中l(wèi)amba表達式的使用

發(fā)布時間:2020-09-21 09:33:16 來源:腳本之家 閱讀:113 作者:遁地龍卷風 欄目:編程語言

(-1)前言

  學習lamba表達式是十分重要的,你會發(fā)現(xiàn)java變的可愛多了。

(0)函數(shù)式接口

  只有一個方法的接口稱為函數(shù)式接口

JButton jButton = new JButton("123");
  jButton.addActionListener(new ActionListener() {
  @Override
  public void actionPerformed(ActionEvent e) {}});

等同于

jButton.addActionListener(e->System.out.println("Hello world"));
  jButton.addActionListener((e)->System.out.println("Hello world"));
  jButton.addActionListener((ActionEvent e)->System.out.println("Hello world"));
  jButton.addActionListener((ActionEvent e)->{System.out.println("Hello world");return;});

a.規(guī)則

  A->B

  A 部分是傳入方法的參數(shù)

  B 部分是函數(shù)體

  參數(shù)類型以及返回類型如果可以通過上下文推斷出來可不寫

   當參數(shù)只有一個而且它的類型可以被推導得知時,該參數(shù)列表外面的括號可以被省略

   當函數(shù)體只有一個語句且返回類型可被推導時{}可省略

b.例子

Runnable runnable = ()->System.out.println(sign);
  Runnable runnable2 = new Runnable() {
  @Override
  public void run() {
  // TODO Auto-generated method stub}
  };
  通過匿名內(nèi)部類我們知道run方法是不需要參數(shù)的
  System.out.println(sign) 相當于run方法的方法體
  Comparator<Integer> lol = (x,y)->x-y;
  Comparator<Integer> lol = (x,y)->{System.out.println(x+y);return x-y;};
  new Comparator<Integer>() {
  @Override
  public int compare(Integer o1, Integer o2) {
  // TODO Auto-generated method stub
  return 0;
  }
};

通過匿名內(nèi)部類我們知道compare方法需要兩個參數(shù)

這時編譯通過Comparator<Integer>中Integer推導出參宿類型及返回類型

c.深入

  lamba表達式可被看做函數(shù),java.util.function定義了常用的函數(shù)式接口

  http://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html

  BiFunction<T,U,R>

  T 代表第一個參數(shù)

  U 代表第二個參數(shù)

  R 代表返回值

  這表時T,U,R都需要編譯器根據(jù)上下文進行類型推導

  Consumer<T>  代表e->System.out.println("Hello world")

  所以當一個方法需要的是lamba表達式時,參數(shù)展現(xiàn)形式是java.util.function中定義的樣式

(2)方法引用

  方法引用是對Lamba表達式的簡化

  類名::方法名(對象方法、類方法)

int[] oop = {3,1,2,1};
  static void sayHello(Integer name)
  {
  System.out.println(123);
  }
  Arrays.stream(oop).forEach(Test::sayHello);
  Arrays.stream(oop).forEach(s->Test.sayHello(s));

  構(gòu)造方法引用:Class::new

  數(shù)組構(gòu)造方法引用:TypeName[]::new

(3)強制類型轉(zhuǎn)換

  有時候編譯器通過上下文推導出的返回類型與實際類型不符時需要進類型轉(zhuǎn)換

Stream<Object> strings = shapelist.stream().<Object>map(s->s.getColor());
  s.getColor())

  s.getColor()返回的是String

(4)lamba表達式在java對象中的應用

你應該在任何java對象中嘗試應用lamba表達式,通則是將這個對象轉(zhuǎn)換成java.util.stream,流有串行并行之分哦!并行流關(guān)鍵字parallelStream

數(shù)組   Arrays.stream()

List、Set   .stream()  

String  String.chars

...

java.util.stream提供了許多方法用來操作流中的數(shù)據(jù),去試一試吧

http://docs.oracle.com/javase/8/docs/api/

java 8英文API,沒有找到中文的...

(2)對流整體的操作

比如我們可以求一個流的的總和

int sum = Arrays.stream(oop).sum();
int sum1 = Arrays.stream(oop).reduce(0,(x,y)->x+y);

(3)集合之間的轉(zhuǎn)換

  我們可以將ArrayList<Shape> 轉(zhuǎn)換成ArrayList<String>、Set<String>、HashMap<String,String>,HashMap<String,Shape>甚至是更復雜的

a.map()

  該方法是映射的意思(一開始我聯(lián)想到了HashMap),還有mapToDouble等

b.collect()

  collect()接受Collectors類型的參數(shù),用來將流重新匯合,

  Collectors是收集器,Collectors.toList(),Collectors.toMap()、Collectors.groupingBy等

c.例子  

public class Shape
  {
  private String color;
  public Shape() {
  // TODO Auto-generated constructor stub
  }
  public String getColor() {
  return color;
  }
  public void setColor(String color) {
  this.color = color;
  }
  public Shape(String color)
  {
  this.color = color;
  }
  }
  ArrayList<String> colorList = new ArrayList<String>(){
  {
  add("Red");
  add("Blue");
  add("Yellow");
  }
  };
  List<Shape> shapeList = colorList.stream().map(Shape::new).collect(Collectors.toList());
  List<String> colos = shpaeList.stream().map(s->s.getColor()).collect(Collectors.toList());
  Set<String> colosSet = shpaeList.stream().map(s->s.getColor()).collect(Collectors.toSet());
  Map<String, String> colorMap = colorList.stream().collect(Collectors.toMap(a->a,s->s));
  Map<String,Shape> shapesMap = shpaeList.stream().collect(Collectors.toMap(s->s.getColor(), s->s));

  Eclipse點不出getColor()方法,還以為用法不對...

  

Map<String,Set<Shape>> shapeMapSet = shpaeList.stream().collect(Collectors.groupingBy(s->s.getColor(),Collectors.toSet()));
  Map<String,Map<String, List<Shape>>> shapeMap3 = shpaeList.stream().collect(Collectors.groupingBy(s->s.getColor(),Collectors.groupingBy(s->s.getColor(),Collectors.toList())));

(4)集合本身的操縱

  想要改變現(xiàn)有集合而不產(chǎn)生新的集合可以使用

 Iterable.forEach(Consumer),Collection.removeAll(Predicate),List.replaceAll(UnaryOperator),List.sort(Comparator)和Map.computeIfAbsent()等
  shpaeList.sort(Comparator.comparing(Shape::getColor));

以上所述是小編給大家介紹的java8中l(wèi)amba表達式的使用,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對億速云網(wǎng)站的支持!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI