java8 Optional使用demo

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;


import org.junit.Test;


public class Lamda1 {


private class Person {
public int no;
private String name;


public Person(int no, String name) {
this.no = no;
this.name = name;
}


public String getName() {
//System.out.println(name);
return name;
}


public int getNo() {
return no;
}


public void setNo(int no) {
this.no = no;
}


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

}




@Test
public void Test1() {

/* // 1. Individual values
Stream stream = Stream.of("a", "b", "c");
// 2. Arrays
String [] strArray = new String[] {"a", "b", "c"};
stream = Stream.of(strArray);
stream = Arrays.stream(strArray);
// 3. Collections
List<String> list = Arrays.asList(strArray);
stream = list.stream();
//清单 5. 数值流的构造
IntStream.of(new int[]{1, 2, 3}).forEach(System.out::println);
IntStream.range(1, 3).forEach(System.out::println);
IntStream.rangeClosed(1, 3).forEach(System.out::println);


*/
List<Integer> nums = Arrays.asList(1, 2, 3, 4);
List<Integer> squareNums = nums.stream().
map(n -> n * n).
collect(Collectors.toList());
//squareNums.stream().forEach(System.out::println);
//清单 9. 一对多


Stream<List<Integer>> inputStream = Stream.of(
Arrays.asList(1),
Arrays.asList(2, 3),
Arrays.asList(4, 5, 6)
);
Stream<Integer> outputStream = inputStream.
flatMap((childList) -> childList.stream());
//清单 10. 留下偶数

Integer[] sixNums = {1, 2, 3, 4, 5, 6};
Integer[] evens =
Stream.of(sixNums).filter(n -> n%2 == 0).toArray(Integer[]::new);
Stream.of(evens).toArray();

//清单 13. peek 对每个元素执行操作并返回一个新的 Stream

List<String> collect2 = Stream.of("one", "two", "three", "four")
.filter(e -> e.length() > 3)
.peek(e -> System.out.println("Filtered value: " + e))
.map(String::toUpperCase)
.peek(e -> System.out.println("Mapped value: " + e))
.collect(Collectors.toList());
collect2.stream().forEachOrdered(System.out::println);

//清单 14. Optional 的两个用例
String strA = " abcd ", strB = null;
print(strA);
print("");
print(strB);
getLength(strA);
getLength("");
getLength(strB);


}

public static void print(String text) {
// Java 8
Optional.ofNullable(text).ifPresent(System.out::println);
 
}

public static int getLength(String text) {
// Java 8
return Optional.ofNullable(text).map(String::length).orElse(-1);
// Pre-Java 8
// return if (text != null) ? text.length() : -1;
};
 
 
 
       @Test
        public void testlamda3() {
        String a="1_2_4_4";
      String string = Optional.of(a).filter((value)->value.split("_").length>4).orElseGet(() -> "111");
      System.out.println(string);
      }
       
// peek 对每个元素执行操作并返回一个新的 Stream 
  @Test
 public void testlamda4() {
           Stream.of("one", "two", "three", "four")
       .filter(e -> e.length() > 3)
       .peek(e -> System.out.println("Filtered value: " + e))
       .map(String::toUpperCase)
       .peek(e -> System.out.println("Mapped value: " + e))
       .collect(Collectors.toList());
}
//清单 15. reduce 的用例           
 @Test
     public void testlamda5() {
 int intArray2 [] = new int[]{20,21,22};  
 
 String arraystring[]=new  String[] {"A", "B", "C", "D"};
 
 Double arraydouble[]=new Double[]{-1.5, 1.0, -3.0, -2.0};
 
 int a=IntStream.of(intArray2).reduce(Integer::min).getAsInt();
 System.out.println(a+"最小值");
// 字符串连接,concat = "ABCD"
  String concat = Stream.of(arraystring).reduce("", String::concat); 
  System.out.println(concat);
  // 求最小值,minValue = -3.0
  double minValue = Stream.of(arraydouble).reduce(Double.MAX_VALUE, Double::min); 
  System.out.println(minValue);
  // 求和,sumValue = 10, 有起始值
  Integer sumValue = Stream.of(1, 2, 3, 4).reduce(Integer::max).get();
  System.out.println(sumValue);
  // 求和,sumValue = 10, 无起始值
  sumValue = Stream.of(1, 2, 3, 11).reduce(Integer::sum).get();
  System.out.println(sumValue);
  // 过滤,字符串连接,concat = "ace"
  concat = Stream.of("a", "B", "c", "D", "e", "F").
   filter(x -> x.compareTo("Z") > 0).
   reduce("", String::concat);
  System.out.println(concat);

//  Stream.generate(intArray2).reduce(0, Integer::sum);

     }
 // limit 和 skip 对运行次数的影响
 @Test
 public void testLimitAndSkip() {
 List<Person> persons = new ArrayList();
 for (int i = 1; i <= 10000; i++) {
 Person person = new Person(i, "name" + i);
 persons.add(person);
 }
List<Person> personList2 = persons.stream()
.filter(p->p.getNo()>100)
.filter(p->p.getNo()>1000)
.limit(10)
.skip(3)
.collect(Collectors.toList());
personList2.stream().forEach(p -> System.out.println(p.getName()));;
}
 
 
//  清单 17. 优化:排序前进行 limit 和 skip
 @Test
public void testLimitAndSkip2() {
 List<Person> persons = new ArrayList<Person>();
 for (int i = 1; i <= 5; i++) {
 Person person = new Person(i, "name" + i);
 persons.add(person);
 }
List<Person> personList2 = persons.stream().sorted((p1, p2) -> 
p1.getName().compareTo(p2.getName())).limit(2).collect(Collectors.toList());
System.out.println(personList2);
personList2.stream().forEach(p -> System.out.println(p.getName()));


 }
 //清单 18. 优化:排序前进行 limit 和 skip
 @Test
 public void testLimitAndSkip3() {
 List<Person> persons = new ArrayList();
 for (int i = 1; i <= 5; i++) {
 Person person = new Person(i, "name" + i);
 persons.add(person);
 }
List<Person> personList2 = persons.stream().limit(2).sorted((p1, p2) -> p1.getName().compareTo(p2.getName())).collect(Collectors.toList());
personList2.stream().forEach(p -> System.out.println(p.getName()));
 }
 //清单 19. 找出最长一行的长度
 @Test
 public void testLimitAndSkip4() throws IOException {
 BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\授权.txt"));
 int longest = br.lines().
  mapToInt(String::length).
  max().
  getAsInt();
 br.close();
 System.out.println(longest);
 
 }
 //清单 20. 找出全文的单词,转小写,并排序
 @Test
 public void testLimitAndSkip6() throws IOException {
 BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\Administrator\\Desktop\\授权.txt"));
 List<String> words = br.lines().
 flatMap(line -> Stream.of(line.split(" "))).
 filter(word -> word.length() > 0).
 map(String::toLowerCase).
 distinct().
 sorted().
 collect(Collectors.toList());
br.close();
System.out.println(words);
 
 }


 
 
 @Test
 public void testLimitAndSkip7() {
 
 List<Person> persons = new ArrayList();
 persons.add(new Person(1, "name" + 1));
 persons.add(new Person(2, "name" + 2));
 persons.add(new Person(3, "name" + 3));
 persons.add(new Person(4, "name" + 4));
 persons.add(new Person(5, "name" + 5));
 boolean isAllAdult = persons.stream().
  allMatch(p -> p.getNo() > 18);
 System.out.println("All are adult? " + isAllAdult);
 boolean isThereAnyChild = persons.stream().
  anyMatch(p -> p.getNo() < 12);
 System.out.println("Any child? " + isThereAnyChild);
 }
 
 //进阶:自己生成流
 @Test
 public void testLimitAndSkip8() {
 Random seed = new Random();
 Supplier<Integer> random = seed::nextInt;
 Stream.generate(random).limit(10).forEach(System.out::println);
 //Another way
 IntStream.generate(() -> (int) (System.nanoTime() % 100)).
 limit(10).forEach(System.out::println);
 
 }
 
 
 @Test
public void test1() {
 Stream.iterate(1, n -> n + 3).limit(10). forEach(x -> System.out.print(x + " "));
String a="a_b_c";

 
 
 @Test
public void test2() {

   //创建Optional实例,也可以通过方法返回值得到。
   Optional<String> name = Optional.of("Sanaulla");
 
   //创建没有值的Optional实例,例如值为'null'
   Optional empty = Optional.ofNullable(null);
 
   //isPresent方法用来检查Optional实例是否有值。
   if (name.isPresent()) {
     //调用get()返回Optional值。
     System.out.println(name.get());
   }
 
   try {
     //在Optional实例上调用get()抛出NoSuchElementException。
     System.out.println(empty.get());
   } catch (NoSuchElementException ex) {
     System.out.println(ex.getMessage());
   }
 
   //ifPresent方法接受lambda表达式参数。
   //如果Optional值不为空,lambda表达式会处理并在其上执行操作。
   name.ifPresent((value) -> {
     System.out.println("The length of the value is: " + value.length());
   });
 
   //如果有值orElse方法会返回Optional实例,否则返回传入的错误信息。
   System.out.println(empty.orElse("There is no value present!"));
   System.out.println(name.orElse("There is some value!"));
 
   //orElseGet与orElse类似,区别在于传入的默认值。
   //orElseGet接受lambda表达式生成默认值。
   System.out.println(empty.orElseGet(() -> "Default Value"));
   System.out.println(name.orElseGet(() -> "Default Value"));
 
   
 
   //map方法通过传入的lambda表达式修改Optonal实例默认值。 
   //lambda表达式返回值会包装为Optional实例。
   Optional<String> upperName = name.map((value) -> value.toUpperCase());
   System.out.println(upperName.orElse("No value found"));
 
   //flatMap与map(Funtion)非常相似,区别在于lambda表达式的返回值。
   //map方法的lambda表达式返回值可以是任何类型,但是返回值会包装成Optional实例。
   //但是flatMap方法的lambda返回值总是Optional类型。
   upperName = name.flatMap((value) -> Optional.of(value.toUpperCase()));
   System.out.println(upperName.orElse("No value found"));
 
   //filter方法检查Optiona值是否满足给定条件。
   //如果满足返回Optional实例值,否则返回空Optional。
   Optional<String> longName = name.filter((value) -> value.length() > 6);
   System.out.println(longName.orElse("The name is less than 6 characters"));
 
   //另一个示例,Optional值不满足给定条件。
   Optional<String> anotherName = Optional.of("Sana");
   Optional<String> shortName = anotherName.filter((value) -> value.length() > 6);
   System.out.println(shortName.orElse("The name is less than 6 characters"));
 }
 //toMap() 方法
 @Test
 public void test3() {
 Stream<String> introStream = Stream.of("Get started with UICollectionView and the photo library".split(" "));
System.out.println(introStream);
 Map<String, String> introMap = introStream.collect(Collectors.toMap(s -> s.substring(0, 1), s -> s));
 System.out.println(introMap); 
 
 
 Stream<String> introStream3 = Stream.of("Get started with UICollectionView and the photo library".split(" "));
 Map<Integer, Set<String>> introMap3 = introStream3.collect(Collectors.toMap(s -> s.length(),
     s -> Collections.singleton(s), (existingValue, newValue) -> {
         HashSet<String> set = new HashSet<>(existingValue);
         set.addAll(newValue);
         return set;
     }));
 introMap3.forEach((k, v) -> {
 if(k==4) {
 System.out.println("这里有4");
 
 }
 
 
 });
 }
 
 
}


猜你喜欢

转载自blog.csdn.net/qq_37749055/article/details/78870512