# Java-Best-Practices-Java8 **Repository Path**: osxfz/Java-Best-Practices-Java8 ## Basic Information - **Project Name**: Java-Best-Practices-Java8 - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-03-16 - **Last Updated**: 2021-03-16 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # Best Practices of Functional Programming in Java 8 ## Lamda Expression Synopsis ### Runnable: ``` Runnable r = () -> System.out.println("Hello world two!"); r.run(); ``` ### Comparator Functions: ``` List personList; Collections.sort(personList, (Person p1, Person p2) -> p1.getSurName().compareTo(p2.getSurName())); ``` ### Function: ``` public String printCustom(Function f) { return f.apply(this); } Function westernStyle = p -> "\nName1: " + " " + p.getSurName(); Function easternStyle = p -> "\nName2: " + " " + p.getSurName(); for (Person person : list1) { System.out.println(person.printCustom(westernStyle)); System.out.println(person.printCustom(easternStyle)); } ``` ### Predicate: ``` Predicate westernStyle = p -> (p.getAge() > 16); Predicate easternStyle = p -> (p.getAge() > 17); for (Person person : list1) { if (westernStyle.test(person)) System.out.println("west "+ person.getSurName()); if (easternStyle.test(person)) System.out.println("east "+person.getSurName()); } ``` ### forEach: ``` List list; list2.forEach(p -> { System.out.println(p.getSurName()); }); ``` ## Stream Synopsis ### Cretion: ``` // We can use Stream.of() to create a stream from similar type of data. // For example, we can create Stream of integers from a group of int or // Integer objects. Stream stream = Stream.of(1, 2, 3, 4); // works fine stream = Stream.of(new Integer[] { 1, 2, 3, 4 }); // Compile time error, Type mismatch: cannot convert from Stream // to Stream // stream1 = Stream.of(new int[]{1,2,3,4}); ``` ### Future: ``` ExecutorService pool = Executors.newFixedThreadPool(3); Future futureTask = getValue("1", "2"); System.out.println("future done? " + futureTask.isDone()); //task may not be done at this stage String result2 = futureTask.get(); //wait till the task is done System.out.println("future done? " + futureTask.isDone()); System.out.print("result: " + result2); public Future getValue(String value1, String value2) { return pool.submit(new Callable() { @Override public String call() throws Exception { Thread.sleep(3000); return value1+value2; } }); } ```