Java 8新機能コード例(注釈付)-メソッドリファレンス、Optional、Stream

7380 ワード

  /**
     * java8       ,java   :               ,          ,  ,       
     * Object    ,       
     * 

* lambda */ @FunctionalInterface interface MyService { void sayMessage(String msg); @Override boolean equals(Object obj); } /** * * @param args */ public static void main(String[] args) { printSeperator(); testMehtodRef(); printSeperator(); testSupplierConsumer(); printSeperator(); testOptional(); printSeperator(); testStream(); printSeperator(); } /** * Optional */ private static void testOptional() { Optional optional1 = Optional.ofNullable(null); // optional , true if (optional1.isPresent()) { System.out.println("optional1 present!"); } // optional , other String res = optional1.orElse("default"); System.out.println("res's value after orElse:" + res); try { /** * , {@link NoSuchElementException} */ res = optional1.orElseThrow(); System.out.println("res's value after orElseThrow:" + res); } catch (NoSuchElementException e) { System.out.println("orElseThrow occured!"); } optional1 = Optional.ofNullable("i have a value"); res = optional1.orElse("default"); System.out.println("res's value after orElse:" + res); } /** * {@link java.util.function.Supplier} and {@link java.util.function.Consumer} */ private static void testSupplierConsumer() { Supplier supplier1 = new Supplier() { @Override public String get() { return new String("hello world from supplier1"); } }; //lambda supplier,supplier , , Supplier supplier2 = () -> new String("hello world from supplier2"); // supplier , var str1 = getSupplier(supplier1); var str2 = getSupplier(supplier2); // supplier, new , , var str3 = getSupplier(String::new); System.out.println("str1: " + str1 + " str2:" + str2 + " str3:" + str3); ///////////////////////////////////////////////////////////////////////////////////////////// Consumer consumer1 = new Consumer() { @Override public void accept(String s) { System.out.print(s + "|"); } }; //lambda Consumer,Consumer , void, Consumer consumer2 = (s) -> System.out.print(s + "^"); var list = getStrList(); list.forEach(consumer1); System.out.println(); list.forEach(consumer2); System.out.println(); ///////////////////////////////////////////////////////////////////////////////////////////// //Predicate , , : , boolean Predicate predicate1 = new Predicate() { @Override public boolean test(Integer integer) { return integer > 2; } }; //lambda Predicate predicate2 = (num) -> num > 2; var numList = getIntList(); var res = numList.stream().filter(predicate1).collect(Collectors.toList()); System.out.println(res); res = numList.stream().filter(predicate2).collect(Collectors.toList()); System.out.println(res); ///////////////////////////////////////////////////////////////////////////////////////////// //Function : , , // , , Function func1 = new Function() { @Override public Character apply(String s) { if (s.length() <= 2) { return 'a'; } return s.charAt(2); } }; Function func2 = (s) -> { return s.length() <= 2 ? 'a' : s.charAt(2); }; var varList = getStrList(); var res2 = varList.stream().map(func1).collect(Collectors.toList()); System.out.println(res2); res2 = varList.stream().map(func2).collect(Collectors.toList()); System.out.println(res2); } /** * {@link java.util.stream.Stream} , * Stream , SQL, : * 1 immediate function * 2 ( ) terminal function */ private static void testStream() { // list, 3 , , , List List numList = getIntList(); List res = numList.stream().filter((num) -> num > 3).map(num -> String.valueOf((char)('a' + num))) .map(str -> String.valueOf((char)('A' + str.charAt(0) - 'a'))).collect(Collectors.toList()); System.out.println(res); final int size = 100; int[] arr = new int[size]; Random random = new Random(); for(int i = 0;i < size;++i){ arr[i] = random.nextInt(1000); } // numArr , 5 , var res2 = Arrays.stream(arr).sorted().limit(5).min(); System.out.println("res2:"+ res2.orElseThrow()); } /** * * * @param supplier * @param * @return */ private static T getSupplier(Supplier supplier) { return supplier.get(); } /** * */ private static void testMehtodRef() { List strs = new ArrayList<>(); strs.add("one"); strs.add("two"); strs.add("three"); strs.add("four"); //printSomething Consumer strs.forEach(HelloJava8::printSomething); System.out.println(); } /** * * * @param s */ private static void printSomething(String s) { System.out.print(s + "\t"); } private static void printSeperator() { System.out.println(SEPERATOR); } /** * , list * * @return */ private static List getStrList() { List strs = new ArrayList<>(); strs.add("one"); strs.add("two"); strs.add("three"); strs.add("four"); return strs; } /** * list * * @return */ private static List getIntList() { List intList = new ArrayList<>(); for (int i = 1; i <= 10; ++i) { intList.add(i); } return intList; }