JDK 8の新しい特性を学習するLamband表現

24920 ワード

JDK 8の発表はもう長い時間がありました。以前から簡単に分かりましたが、まだ分かりません。今日は時間を割いて整理しました。訂正を歓迎します。JDK 8新特の一つ:
ラボンダ(λ)   -- 公式サイト
Lamdaは実際に匿名の方法である。
@Test
public void oldRunable() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            System.out.println("The old runable now is using!");
        }
    }).start();
}
Lamda表現:
@Test
public void runable() {
    new Thread(() -> System.out.println("It's a lambda function!")).start();
}
Lambadaのタイプは「ターゲットタイプ」と呼ばれ、JDK 8が導入した概念です。その定義は、インターフェースが明示的な声明の抽象的な方法だけであれば、彼は関数インターフェースであり、一般的に@Funtional Interfaceで表記されています。例:
@FunctionalInterface
public interface Runnable { void run(); }
public interface Callable<V> { V call() throws Exception; }
public interface ActionListener { void actionPerformed(ActionEvent e); }
public interface Comparator<T> { int compare(T o1, T o2); boolean equals(Object obj); }
     Comparator       2   ,        。    equals   Object ,         Object public  (  ) ,           。 
   
  

Lambda , :

  • :(Method Reference)
  • :(Default Method)
  • Lambda API(New and Enhanced APIs That Take Advantage of Lambda Expressions and Streams in Java SE 8)

, :

class Person{
    @Getter
    Integer age;
    @Getter
    String name;
    @Getter
    String firstName;

    Person(Integer age){
        this.age = age;
    }
    Person(Integer age, String name){
        this.age = age;
        this.name = name;
    }
    Person(String name, String firstName, Integer age){
        this.name = name;
        this.firstName = firstName;
        this.age = age;
    }

    public static int compare(Person a, Person b){
        return a.getAge().compareTo(b.getAge());
    }
}

    @Test
    public void test(){
        // list   
        ArrayList list = new ArrayList<>();
        list.add(new Person(30));
        list.add(new Person(40));
        list.add(new Person(10));
        System.out.println(list);

        list.forEach(a->{System.out.println(a.getAge());});
//        list.sort((a,b)-> b.getAge().compareTo(a.getAge())); //     
        list.sort(Comparator.comparing(Person::getAge)); //       
        System.out.println(list);

        //     
        Person[] people = new Person[]{
                new Person("name1", "f1", 20),
                new Person("name2", "u2",30),
                new Person("name3", "p3",10),
                new Person("name4R", "r4",60),
        };
        for(Person p : people){
            System.out.println(p.getAge());
        }
        System.out.println("             --       ");
        //    
//        Arrays.sort(people, (a,b)->  a.getAge().compareTo(b.getAge())); //     
        //    
//        Arrays.sort(people, (a, b) -> Person.compare(a,b)); //       
        //    
//        Arrays.sort(people, Person::compare); //         (         )
//        for(Person p : people){
//            System.out.println(p.getAge());
//        }

        Arrays.sort(people, Comparator.comparing(Person::getFirstName)); //       
        for (Person p: people){
            System.out.println(p.getFirstName());
        }

    }
, :
 
   
  
public class LambdaTest {

    //      
    public static
    <T, SOURCE extends Collection<T>, DEST extends Collection<T>> DEST transfer(
        SOURCE source, Supplier<DEST> collectionFactory
    ){
        DEST result = collectionFactory.get();
        for (T t : source) {
            result.add(t);
        }
        return result;
    }

	
    @Test
    public void test1(){
        ArrayList list = new ArrayList<>();
list.add( new Person( 40 )) ; list.add(new Person(10)); System.out.println(list); list.forEach(a->{System.out.println(a.getAge());}); Set personSet = transfer(list, ()->new HashSet<>()); System.out.println(personSet); // - personSet = transfer(list, HashSet::new); System.out.println(personSet); // - list.add(new Person(99)); // personSet = transfer(list, HashSet::new); System.out.println(personSet); // - }
 
  } 
  

lambda :

new HashSet();  ==   HashSet::new   ==   HashSet::new


, :

  • , , , default  。 , 。
  • ( , , )


Java8 : (stream)。 , 。 API (pipelines) 。 。 IO API StringBuffer append , 。 :

@Test
public void test2(){
    // list   
    ArrayList list = new ArrayList<>();
    list.add(new Person("name1", "f1", 20));
    list.add(new Person("name2", "u2",30));
    list.add(new Person("name3", "p3",10));
    list.add(new Person("name4R", "r4",60));
    System.out.println(list);
    list.forEach(a->{System.out.println(a.getAge());});

    //     
    List newL = list.stream().filter(a -> a.getFirstName().equals("test1")).distinct().collect(Collectors.toList());
    System.out.println(newL);
    newL = list.stream().map(a -> Integer.valueOf(a.getAge())).filter(a -> a>20).collect(Collectors.toList());
    System.out.println(newL);
    newL.forEach(a->{System.out.println(a);});
}

.stream  , :list.stream
.map , :.map(m -> new Integer(m))
.filter  , :.filter(a -> a.getA == a)
.forEach  ,forEachordered , , : .forEach(a -> System.out.println(a);)
.distinct  , :list.stream.distinct()
.collect  , : .collect(Collectors.toList());
.toArray 
.reduce  ( , ), :.reduce(a)
.sorted 
.findFirst
.findAny  , Optional
.flatmap 
.limit 
.max  ,min
.peek 
.skip 
.allMatch  , true。 anyMatch,noneMatch
.count