I have problem with understand why String[] args
variable has no forEach
method? I can not find any information that this type is not Serializable or Collection because forEach
methos implements Serializable.
For example, I have simple main Java class. If I want to use forEach
method, I have to first import Arrays
class and then on stream
use forEach
method like below:
import java.util.Arrays;
public class MyClass {
public static void main(String[] args) {
Arrays.stream(args).forEach(System.out::println);
}
}
Why it is not possible to make it just simple like this?
args.forEach(System.out::println);
Short answer: Arrays don't have a forEach
method defined on them.
Longer answer: Because it doesn't need it. An array type (using []
, not List<>
) represents a low level structure in memory, more suited to low level optimisations rather than higher level functional-style code. The hardware of a machine much more closely resembles the imperative, stateful style from languages like C, rather than the functional stateless style from languages like Haskell. Because of this, when creating a lower level data structure like a basic array, it doesn't necessarily make sense to give it more advanced functionality. If you really want a forEach()
method, trivially wrap it using Arrays.asList()
, Arrays.stream()
, or List.of()
(depending on Java version).