Why list of String has no forEach method?
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).
The main method takes one parameter of type String[]
. Which is an Array
of String
s.
List
s and Array
s are two different things and only the former does provide a foreach method.
Not just String array, Array of any object or primitive types do not have this feature since arrays are the data stricture that is different from other collection implementations