title: stream and functional interface
date: 2019-07-24 14:03:02
categories:
- java Foundation
tags:
- 1. Mind Mapping
- 2. Stream and Functional Interface
1. Mind Mapping
2. Stream and Functional Interface
2.1. Acquisition stream
- All Collection collections can obtain streams by stream default method
- The static method of Stream interface can get the stream corresponding to the array.
- Map is not a collection type, so we need to get the corresponding flow according to key, value, entry respectively.
2.2. Flow method
2.2.1. forEach
- void forEach(Consumer<? super T> action);
2.2.2. filter
- Stream filter(Predicate<? super T> predicate);
2.2.3. map
Mapping elements in a stream to another stream is usually used to convert them to another type
- Stream map(Function<? super T, ? extends R> mapper);
2.2.4. count
- long count();
2.2.5. limit
- Stream limit(long maxSize);
2.2.6. skip
- Stream skip(long n);
2.2.7. concat
- static Stream concat(Stream<? extends T> a, Stream<? extends T> b)
2.3. Use of collect
2.3.1. Convert to list
- collect.()
2.3.2. Convert to map
Pass in key, value
- public static <T,K,U> Collector<T,?,Map<K,U>> toMap(Function<? super T,? extends K> keyMapper,
Function<? super T,? extends U> valueMapper) - For example: Stream. concat (one. stream (), two. stream (). collect (Collectors. toMap (s - > s, s - > New Person (s));
2.4. Exercise of Flow Method
package javaBase.Stream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author jhmarryme.cn * @date 2019/7/24 11:21 */ public class StreamAndFunctionalInterface { /** * Combining various methods of test flow with the use of common functional interfaces * @param args */ public static void main(String[] args) { ArrayList<String> one = new ArrayList<>(); one.add("Di Ali Gerba"); one.add("Song Yuan Qiao"); one.add("Su Xing He"); one.add("Shi Tian Tian"); one.add("Stone jade"); one.add("Lao Tzu"); one.add("Chuang-tzu"); one.add("Master Hongqi"); //Second team ArrayList<String> two = new ArrayList<>(); two.add("Guli Nazha"); two.add("Zhang Wuji"); two.add("Zhao Liying"); two.add("Xie"); two.add("Zhao Si"); two.add("Zhang Tian AI"); two.add("Zhang Er dog"); // 1. the first team name is only 3 characters, and is stored in a new collection. one.stream().filter(s -> s.length() == 3).collect(Collectors.toList()).forEach(s -> System.out.println(s)); System.out.println("------------"); // 2. After the first team is screened, only the first three people are needed; they are stored in a new set. one.stream().limit(3).collect(Collectors.toList()).forEach(s -> System.out.println(s)); System.out.println("------------"); // 3. second teams need only the names of Zhang's members and store them in a new collection. two.stream().filter(s -> s.startsWith("Zhang")).collect(Collectors.toList()).forEach(s -> System.out.println(s)); System.out.println("------------"); // 4. Don't use the first two people after the second team is screened; store them in a new collection. two.stream().skip(2).collect(Collectors.toList()).forEach(s -> System.out.println(s)); System.out.println("------------"); // 5. Merge two teams into one team; store them in a new set. Stream<String> stream = Stream.concat(one.stream(), two.stream()); // stream.collect(Collectors.toList()).forEach(s -> System.out.println(s)); System.out.println("------------"); // 6. create `Person` objects by name; store them in a new collection. // 7. Print the whole team's Person object information. stream.map(s -> { return new Person(s); }).collect(Collectors.toList()).forEach(person -> System.out.println(person.toString())); //8. Additionally, map list to map final Map<String, Person> map = Stream.concat(one.stream(), two.stream()).collect(Collectors.toMap(s -> s, s -> new Person(s))); final Set<Map.Entry<String, Person>> entries = map.entrySet(); for (Map.Entry<String, Person> entry : entries) { System.out.print(entry.getKey()); System.out.println(" : " + entry.getValue().toString()); } //Converting an int array to a list int[] arr = {1,2,3,2,2,2,5,4,2}; //boxed boxing final List<Integer> collect = Arrays.stream(arr).boxed().collect(Collectors.toList()); final Iterator<Integer> iterator = collect.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next() + " "); } //Convert list to int [], because int is not a wrapper type and needs to be converted final int[] array = collect.stream().mapToInt(Integer::intValue).toArray(); for (int i : array) { System.out.print(i + " "); } } }
2.5. Functional Interface
An interface with and only one abstract method
2.5.1. Supplier
Produce a data
- T get()
2.5.2. Consumer
It's about consuming a data.
- void accept(T t)
- Default method: andThen
2.5.3. Predicate
Judgment of a certain type of data
- boolean test(T t)
- Default method: and or negate
2.5.4. Function<T,R>
Getting another type of data from one type of data
- R apply(T t)
- Default method: andThen
2.6. Practice of Functional Interface Method
2.6.1. Comparator
package javaBase.functionalInterface.functionalInterfaceDemo; import java.util.Arrays; /** * Using lambda expression as comparator * @author jhmarryme.cn * @date 2019/7/22 9:43 */ public class LambdaForComparatorDemo { public static void main(String[] args) { String[] array = { "abc", "ab", "abcd" }; System.out.println(Arrays.toString(array)); Arrays.sort(array, (a, b) -> { return a.length() - b.length(); }); System.out.println(Arrays.toString(array)); } }
2.6.2. consumer
package javaBase.functionalInterface.functionalInterfaceDemo; import java.util.function.Consumer; /** * Testing Consumer Interface * Consumption of data for a specified generic type with no return value * Operations can be combined through andThen * @author jhmarryme.cn * @date 2019/7/22 11:21 */ public class LambdaForConsumerDemo { public static void consumerString(String[] info, Consumer<String> con1, Consumer<String> con2, Consumer<String> con3){ for (String s : info) { con1.andThen(con2).andThen(con3).accept(s); } } public static void main(String[] args) { String[] array = { "Di Ali Gerba,female, 14", "Guli Nazha,female, 12", "Mar Zaha,male, 121" }; consumerString(array, s -> System.out.print("Full name: " + s.split(",")[0]), s -> System.out.print("Gender: " + s.split(",")[1]), s -> System.out.println("Age: " + s.split(",")[2]) ); } }
2.6.3. supplier
package javaBase.functionalInterface.functionalInterfaceDemo; import java.util.function.Supplier; /** * Testing Supplier Interface * Contains a nonparametric method for obtaining object data of a generic parameter specified type * @author jhmarryme.cn * @date 2019/7/22 9:52 */ public class LambdaForSupplierDemo { public static void main(String[] args) { /*String msgA = "Hello"; String msgB = "World"; System.out.println(getString(() -> msgA + msgB));*/ int arr[] = {2,3,4,52,333,23}; System.out.println(getMax(() -> { int max = arr[0]; for (int i : arr) { max = i > max ? i : max; } return max; })); } public static int getMax(Supplier<Integer> integerSupplier){ return integerSupplier.get(); } public static String getString(Supplier<String> stringSupplier){ return stringSupplier.get(); } }
2.6.4. function
package javaBase.functionalInterface.functionalInterfaceDemo; import java.util.function.Function; /** * Practice function interface through functional structure * Getting another type of data from one type of data, the former is called the pre-condition, the latter is called the post-condition. * @author jhmarryme.cn * @date 2019/7/22 13:15 */ public class LambdaForFunctionDemo { /** * Generics based on interfaces * apply The parameter type in the method is String, returning Integer * @param integerFunction */ public static void method(Function<String, Integer> integerFunction){ final Integer apply = integerFunction.apply("5"); System.out.println(apply + 20); } /** * Processing on the basis of the previous function * The first generic type of the second function must be the last generic type of the previous function. * The result of the former is Integer, and the latter must be received by Integer. * @param f1 * @param f2 */ public static void methood(Function<String, Integer> f1, Function<Integer, Integer> f2){ final Integer apply = f1.andThen(f2).apply("1"); System.out.println(apply); } /** * Intercept the part of the number and add 100 to the result. * @param str * @param f1 * @param f2 * @return */ public static Integer getAgeNum(String str, Function<String, Integer> f1, Function<Integer, Integer> f2){ return f1.andThen(f2).apply(str); } public static void main(String[] args) { // method((s) -> Integer.parseInt(s)); // methood(s -> Integer.parseInt(s)+1, i -> i = ((int)Math.pow(i, 10))); String str = "Zhao Liying,20"; final Integer ageNum = getAgeNum(str, s -> Integer.parseInt(s.split(",")[1]), i -> i = i + 100 ); System.out.println(ageNum); } }
2.6.5. predicate
package javaBase.functionalInterface.functionalInterfaceDemo; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; /** * Practice predicate-related methods through functional interfaces * The generic specified data type is judged and a Boolean value is obtained. * Containing and or not, or, negate * @author jhmarryme.cn * @date 2019/7/22 12:54 */ public class LambdaForPredicateDemo { public static Boolean method( Predicate<String> stringPredicate){ return stringPredicate.test("helloWorld"); } public static void method(Predicate<String> p1, Predicate<String> p2){ final boolean helloWorld = p1.or(p2).test("HelloWorld"); System.out.println(helloWorld); } public static ArrayList<String> filterString(String[] arr, Predicate<String> stringPredicate){ final ArrayList<String> list = new ArrayList<>(); for (String s : arr) { if (stringPredicate.test(s)) { list.add(s); } } return list; } public static void main(String[] args) { /*System.out.println(method(s -> { return s.length() > 5; })); */ // method(s -> s.contains("el"), s -> s.length() > 10); /** * Screening conditions: * Must be for girls; * The name is 4 words. */ String[] array = { "Di Ali Gerba,female", "Guli Nazha,female", "Mar Zaha,male", "Zhao Liying,female" }; final ArrayList<String> arrayList = filterString(array, s -> { return s.split(",")[1].equals("female") && s.split(",")[0].length() == 4; }); for (String s : arrayList) { System.out.println(s); } } }
2.6.6. lambda Delayed Loading
package javaBase.functionalInterface.DelayForLambda; import static javaBase.functionalInterface.DelayForLambda.MessageBuilder.MAX_NUM; /** * Testing delayed execution of lambda expressions * Optimize performance, and lambda content is not executed when conditions are not met * @author jhmarryme.cn * @date 2019/7/22 9:32 */ public class DelayForLambdaDemo { public static void log(int level, MessageBuilder builder){ if (level == 1) { System.out.println(builder.messageBuilder()); } } public static void main(String[] args) { String msgA = "Hello"; String msgB = "World"; String msgC = "Java"; //The splicing string here will not be executed if conditions do not hold. log(1, () -> msgA + msgB + msgC ); } } package javaBase.functionalInterface.DelayForLambda; /** * @author jhmarryme.cn * @date 2019/7/22 9:33 */ @FunctionalInterface public interface MessageBuilder { int MAX_NUM = 97; /** * Testing lambda delayed loading * @return */ String messageBuilder(); }