The Stream API
is a feature introduced in Java8. It is for handling aggregates such as arrays and collections.
It is a convenient API that can aggregate values and process using data.
By using Stream, the extended for statement can be simplified.
public class Sample {
public static void main(String[] args) {
List<String> JS = new ArrayList<>(Arrays.asList("Vue", "React", "Angular"));
long count = JS.stream().count();
System.out.println(count); // 3
}
}
The following is the process to remove "Angular" and display the list.
public class Sample {
public static void main(String[] args) {
List<String> JS = new ArrayList<>(Arrays.asList("Vue", "React", "Angular"));
JS.stream()
.filter(s -> !s.equals("Angular"))
.forEach(System.out::println); // Vue React
}
}
The second sorted method is in descending order because the reverseOrder method of the Comparator interface is specified as an argument.
public class Sample {
public static void main(String[] args) {
List<String> JS = new ArrayList<>(Arrays.asList("Vue", "React", "Angular"));
JS.stream()
.sorted() //Ascending order because no arguments are passed
.forEach(System.out::println); // Angular React Vue
JS.stream()
.sorted(Comparator.reverseOrder()) //In descending order
.forEach(System.out::println); // Vue React Angular
}
}
The allMatch
method returns true
if they all match.
public class Sample {
public static void main(String[] args) {
List<Integer> num1 = new ArrayList<>(Arrays.asList(10,38,3));
boolean a = num1.stream()
.allMatch(b -> b > 10); //Are all elements greater than 10
System.out.println(a); //false
boolean c = num1.stream()
.allMatch(d -> d > 1); //Are all elements greater than 1
System.out.println(c); //true
}
}
The anyMatch
method returns true if at least one matches.
public class Sample {
public static void main(String[] args) {
List<Integer> num1 = new ArrayList<>(Arrays.asList(10,38,3));
boolean a = num1.stream()
.anyMatch(b -> b > 40); //Are there any elements greater than 40?
System.out.println(a); //false
boolean c = num1.stream()
.anyMatch(d -> d > 30); //Are there any elements greater than 30
System.out.println(c); //true
}
}
The noneMatch
method returns true
if there are no matches.
public class Sample {
public static void main(String[] args) {
List<Integer> num1 = new ArrayList<>(Arrays.asList(10,38,3));
boolean a = num1.stream()
.noneMatch(b -> b > 7); //Is there any element larger than 7?
System.out.println(a); //false
boolean c = num1.stream()
.noneMatch(d -> d > 40); //Is there any element larger than 40?
System.out.println(c); //true
}
}
Interface Stream Java8 StreamAPI
Recommended Posts