dakaizou

Java lambda expression

Apr 19th, 2022 (edited)
285
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | None | 0 0
  1. // src/edu/umb/cs680/test/App.java
  2. package edu.umb.cs680.test;
  3.  
  4. import edu.umb.cs680.test.other.Other;
  5.  
  6. public class App {
  7.     public static void main(String[] args) {
  8.         Other someNumbers = new Other();
  9.         int y = 2;
  10.        
  11.         // This lambda expression doesn't have acess to <Other.sort>'s local context
  12.         // since its enclosing method is App.main
  13.         // it can only access y not x
  14.         // similarly, the enclosing class is App, not Other
  15.         someNumbers.sort((a, b) -> {
  16.             System.out.println(y);
  17.             // System.out.println(x);
  18.             return a - b;
  19.         });
  20.     }
  21. }
  22.  
  23. // src/edu/umb/cs680/test/other/Other.java
  24. package edu.umb.cs680.test.other;
  25.  
  26. import java.util.ArrayList;
  27. import java.util.Collections;
  28. import java.util.Comparator;
  29.  
  30. public class Other {
  31.     private ArrayList<Integer> numbers;
  32.  
  33.     public Other() {
  34.         numbers = new ArrayList<Integer>();
  35.         for (int i = 0; i < 10; i++) {
  36.             numbers.add(Integer.valueOf(i));
  37.         }
  38.     }
  39.  
  40.     public void sort(Comparator<Integer> comparator) {
  41.         int x = 1;
  42.         Collections.sort(numbers, comparator);
  43.     }
  44. }
Add Comment
Please, Sign In to add comment