JAva lambda式と関数式インタフェースの使用例

61856 ワード


import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;

import org.junit.Test;

/**
 * @author gm
 * Lambda          :java8           "->" ,            lambda   
 *            lambda      :
 *        :lambda        
 *        :lambda           , lambda 
 *       :   ,    
 *      () -> System.out.println("xxxxxx");
 *       :     ,    
 *      (x) -> System.out.println(x);
 *       :       ,         
 *      x -> System.out.println(x);
 *       :        ,    ,  lambda           test4
 *      Comparator comparator = (x,y) -> {
 *            System.out.println("     ");
 *            return Integer.compare(x, y);
 *        };
 *         : lambda        , return           
 *        Comparator comparator = (x,y) -> Integer.compare(x, y);
 *         :lambda                   ,  jvm                 , “    ”
 *        (Integer x,Integer y) -> Integer.compare(x, y);  == (x,y) -> Integer.compare(x, y);
 *    
 *           (                 ),        (           )
 *
 *     、lambda             
 *             :              (              ),     @FunctionalInterface     
 *            :jdk    @FunctionalInterface          
 */
public class TestLambda {
    
	@Test
	public void test1() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				System.out.println("hello lambda1");
			}
		}).start();

		//        Runable    run      .                
		Runnable r1 = () -> System.out.println("hello lambda2");
		new Thread(r1).start();
	}
	
	// Consumer   accept              ,      ,     
	@Test
	public void test2() {
		//          ,         ,        ,          
		// Consumer             , accept               ,    。            accept
		Consumer<String> consumer = x -> System.out.println(x);
		consumer.accept("   ");
	}
	
	// Consumer  andThen  ,                    
	@Test
	public void test3() {
		//          ,         ,        ,          
		// Consumer             , andThen                      
		Consumer<String> consumer = x -> System.out.println(x);
		Consumer<String> consumer2 = x -> System.out.println("   ,        !");
		consumer.andThen(consumer2).accept("     ?");
	}

	@Test
	public void test4() {
		//          ,      ,       ,     。      Comparator   compare  ,  collection    
		Comparator<Integer> comparator = (x, y) -> {
			System.out.println("     ");
			return Integer.compare(x, y);
		};
		//      ,     
		Comparator<Integer> comparator2 = (x, y) -> Integer.compare(y, x);

		Integer[] array = { 1, 9, 6, 7, 3, 2, 8 };
		List<Integer> list = Arrays.asList(array);
		list.sort(comparator);
		System.out.println(list);
		list.sort(comparator2);
		System.out.println(list);
	}

	//        lambda  ,                  ,        ,     ,        
	@Test
	public void test5() {
		// (x) -> (x + 1)   lambda   ,     。
		//                    ,      MyFun,         MyFun   getValue   。
		//      MyFun   getValue               
		Integer result = operation(100, (x) -> (x + 1));
		//     101
		System.out.println(result);
		//     ,  getValue        ,       99
		System.out.println(operation(100, (x) -> (x - 1)));
	}

	public Integer operation(Integer num, MyFun<Integer> mf) {
		return mf.getValue(num);
	}

	List<User> users = Arrays.asList(new User("zhangsan", 24, 7500), new User("lisi", 25, 13000), new User("wangwu", 26, 20000));

	@Test
	public void test6() {
		//         lambda   ,          Comparator compare  
		Collections.sort(users, (u1, u2) -> {
			return u1.getAge() - u2.getAge();
		});
		System.out.println(users);
	}

	@Test
	//    long     
	public void test7() {
		//   3 lambda,         。   MyFun2 getValue(a,b)     a+b
		op(100L, 200L, (x, y) -> x + y);
	}

	public void op(Long t1, Long t2, MyFun2<Long, Long> mf2) {
		System.out.println(mf2.getValue(t1, t2));
	}

	@Test
	public void test8() {
		//    stream  lambda       。stream         list
		// (e) -> e.getSalary() >= 10000      Predicate   test   ,          
		//         list     salary    10000,         
		// forEach      。           list,  salary  10000 User
		users.stream().filter((e) -> e.getSalary() >= 10000).forEach(System.out::println);
		users.stream().map((e) -> e.getName()).forEach(System.out::println);
	}
}

@FunctionalInterface
public interface MyFun<T> {
	public T getValue(T value);
}
@FunctionalInterface
public interface MyFun2<T, R> {

	public R getValue(T t1, T t2);
}

public class User {
	private String name;
	private int age;
	private int salary;

	public User() {
	}

	public User(String name, int age, int salary) {
		super();
		this.name = name;
		this.age = age;
		this.salary = salary;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public int getSalary() {
		return salary;
	}

	public void setSalary(int salary) {
		this.salary = salary;
	}

}
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import org.junit.Test;

/**
 * @author gm
 * java8             
 * 
 * Consumer:      ,       
 *         void accept(T t);
 * Supplier:      ,      
 *         T get()
 * Function:      ,    ,    
 *         R apply(T t);
 * Predicate:      ,          (     true)
 *         boolean test(T t);
 *
 */
public class TestLambdaFunc {

	@Test
	// Consumer      
	public void testConsumer() {
		// Consumer      ,                  。               。
		// m -> System.out.println("  :" + m + "  ")      Consumer accept(T t)     
		// m -> System.out.println(" " + m + "   ,     ")                    
		happy(10000L, m -> System.out.println("  :" + m + "  "), m -> System.out.println(" " + m + "   ,     "));
	}

	public void happy(double money, Consumer<Double> con, Consumer<Double> con2) {
		con.andThen(con2).accept(money);
	}
    
	// Supplier      
	@Test
	public void testSupplier() {
		// Supplier      。            。       
		// () -> (int)(Math.random() * 100)         ,        
		List<Integer> numList = getNumList(10, () -> (int) (Math.random() * 100));
		System.out.println(numList);
	}
    
	public List<Integer> getNumList(int num, Supplier<Integer> sup) {
		List<Integer> list = new ArrayList<>();

		for (int i = 0; i < num; i++) {
			Integer n = sup.get();
			list.add(n);
		}
		return list;
	}
    
	// Function      
	@Test
	public void testFunction() {
		//            ,                ,              (    ,   )
		// (x) -> (x + ",    ")     Function   apply   
		String str = strHandler("   ", (x) -> (x + ",    "));
		System.out.println(str);
	}

	private String strHandler(String str, Function<String, String> fun) {
		return fun.apply(str);
	}
    
	// Predicate      
	@Test
	public void testPredicate() {
		List<String> list = Arrays.asList("Hello", "World", "www.baidu.com");
		//      Predicate      ,x -> (x.length() > 5)               5
		List<String> filterStr = filterStr(list, x -> (x.length() > 5));
		System.out.println(filterStr);
	}

	public List<String> filterStr(List<String> list, Predicate<String> pre) {
		List<String> strList = new ArrayList<>();

		for (String str : list) {
			if (pre.test(str)) {
				strList.add(str);
			}
		}
		return strList;
	}
}

import java.io.PrintStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Supplier;

import org.junit.Test;

/**
 * @author gm
 *     : lambda             ,      “    ”
 *         (          lambda            )
 *          :
 *           ::     
 *          ::     
 *          ::     
 *   :
 *     1.lambda                 ,                         
 *  2. lambda                     ,               ,    className::method
 *  
 *   、     
 *    :
 *      ClassName::new
 */
public class TestMethodRef {

	//   ::     
	@Test
	public void test() {
		Consumer<String> consuemr = (x) -> System.out.println(x);
		consuemr.accept("aaaa");

		PrintStream ps = System.out;
		Consumer<String> consumer2 = ps::println;
		consumer2.accept("bbbb");
	}
    
	@Test
	public void test2() {
		User user = new User("gm", 30, 200000);
		//      ,       ()
		Supplier<String> sup = () -> user.getName();
		System.out.println(sup.get());

		//    lambda        。() -> user.getAge() == user::getAge
		Supplier<Integer> sup2 = user::getAge;
		System.out.println(sup2.get());
	}
    
	//  ::     
	@Test
	public void test3() {
		Comparator<Integer> com = (x, y) -> Integer.compare(y, x);

		//        lambda            。        
		Comparator<Integer> com1 = Integer::compare;

		Integer[] array = { 1, 9, 6, 7, 3, 2, 8 };
		List<Integer> list = Arrays.asList(array);
		list.sort(com);
		System.out.println(list);

		list.sort(com1);
		System.out.println(list);
	}
    
	//  ::     
	@Test
	public void test4() {
		BiPredicate<String, String> bp = (x, y) -> x.equals(y);

		//        ,                ,           
		//               ,       ,                ,         
		BiPredicate<String, String> bp2 = String::equals;
		System.out.println(bp.test("1", "1"));
		System.out.println(bp2.test("Hello", "World"));
	}

	@Test
	public void test5() {
		//              new User();
		//   Supplier  ,   User  ,              ,       
		Supplier<User> sup = () -> new User();
		//       ,    
		Supplier<User> sup2 = User::new;
		//   get()  ,            ,        
		System.out.println(sup.get());
		//   get        ,        
		System.out.println(sup2.get());
	}
}