Java
Are you using it!
I often write something lately, but I feel that it has become quite convenient since the Stream API
was implemented.
Typical things like Stream.forEach
and Stream.filter
come out at once,
Some things that I don't use often don't come out, so I'll keep them for memorandum.
Stream.generate Creates an unordered, infinite Stream. This is useful when creating irrelevant values, such as generating random numbers.
Document: docs
public static void main(String[] args) {
Stream<Double> stream = Stream.generate(() -> Math.random());
stream.limit(5).forEach(System.out::println);
}
0.022804976867977667
0.06422820749702451
0.7240936837411123
0.9070898332933144
0.6724389714182997
Stream.anyMatch
With Predicate <T>
as a parameter, true is returned if there is at least one value that matches the condition.
Documentation: docs
public static void main(String[] args) {
List<String> strList = Arrays.asList("dog", "cat", "bird");
boolean match = strList.stream().anyMatch(e -> e.equals("dog"));
System.out.println(match);
}
true
Stream.allMatch
With Predicate <T>
as a parameter, true is returned if all the values match the conditions.
Documentation: docs
public static void main(String[] args) {
List<String> strList = Arrays.asList("dog", "cat", "bird");
boolean match = strList.stream().allMatch(e -> e.equals("dog"));
System.out.println(match);
}
false
Stream.noneMatch
With Predicate <T>
as a parameter, it returns true if there is no value that matches the condition.
Documentation: docs
public static void main(String[] args) {
List<String> strList = Arrays.asList("dog", "cat", "bird");
boolean match = strList.stream().noneMatch(e -> e.equals("fish"));
System.out.println(match);
}
true
Stream.takeWhile
With Predicate <T>
as a parameter, the value is returned while the conditions are met.
In the example below, numbers less than 0 will be returned.
Document: docs
public static void main(String[] args) {
List<Integer> numList = Arrays.asList(
-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5
);
numList.stream().takeWhile(x -> x < 0).forEach(System.out::println);
}
-5
-4
-3
-2
-1
Stream.dropWhile
With Predicate <T>
as a parameter, the value is returned while the conditions are not met.
In the example below, numbers greater than or equal to 0 will be returned.
Document: docs
public static void main(String[] args) {
List<Integer> numList = Arrays.asList(
-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5
);
numList.stream().dropWhile(x -> x < 0).forEach(System.out::println);
}
0
1
2
3
4
5
StreamAPI
It's very convenient, isn't it?
I would like to actively use it and aim for a code that can be understood intuitively.
It ’s short, but that ’s it. Thank you very much!
Recommended Posts