One, function-type programming
1. Lambda expression
parameter values, function body content, for example:
Before Java 8:
New Thread (New Runnable () {
@Override
public void Run () {
System.out.println ("Before Java8, too much code for too little");
}
}). Start ();
Java 8 Way:
New Thread ((), System.out.println ("in Java8, Lambda expression Rocks!"). Start ();
Other usage scenarios are: event handling, event monitoring code, iteration of the list (List.foreach (n-System.out.println (n));)
2. Method reference
Some lambda expressions simply execute a method call. In this case, without a lambda expression, it is easier to refer to the method directly by means of the method name, which is a method reference, a more concise and understandable type of lambda expression.
Arrays.sort (Stringsarray, string::comparetoignorecase);
is equivalent to
Arrays.sort (Stringsarray, (s1,s2)->s1.comparetoignorecase (S2));
shorthand for a method that already exists in a lambda expression directly from a method reference
Ii. Collection of new operations
1. Create a string list by filtering
// 创建一个字符串列表,每个字符串长度大于2
List<String> filtered = strList.stream().filter(x -> x.length()>
2
).collect(Collectors.toList());
2. Apply a function to each element of the list
// 将字符串换成大写并用逗号链接起来
List<String> G7 = Arrays.asList(
"USA"
,
"Japan"
,
"France"
,
"Germany"
,
"Italy"
,
"U.K."
,
"Canada"
);
String G7Countries = G7.stream().map(x -> x.toUpperCase()).collect(Collectors.joining(
", "
));
System.out.println(G7Countries);
3. Remove duplicate elements
List<Integer> numbers = Arrays.asList(
9
,
10
,
3
,
4
,
7
,
3
,
4
);
List<Integer> distinct = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());
4. Calculate the maximum, minimum, sum, and average values of the SET elements
List<Integer> primes = Arrays.asList(
2
,
3
,
5
,
7
,
11
,
13
,
17
,
19
,
23
,
29
);
IntSummaryStatistics stats = primes.stream().mapToInt((x) -> x).summaryStatistics();
System.out.println(
"Highest prime number in List : "
+ stats.getMax());
System.out.println(
"Lowest prime number in List : "
+ stats.getMin());
System.out.println(
"Sum of all prime numbers : "
+ stats.getSum());
System.out.println(
"Average of all prime numbers : "
+ stats.getAverage());
New features in Java 8