Reputation: 548
Is there any comprehensive way to invoke a method on every value in a an array without having to create a for loop? It seems like it would be trivial, but I am unable to find anything.
For example:
class Foo{
public static void main(String[] args){
String[] arr = {"1","2","3"};
int[] intarr = new int[arr.length];
for(int i = 0; i < arr.length; i++){
intarr[i] = Integer.parseInt(arr[i]);
}
}
}
is there any way to do this without a for loop?
Upvotes: 0
Views: 120
Reputation: 11483
Depends on your Java version:
Pre Java 8:
List<String> lis = new ArrayList<>(Arrays.asList(arr));
Iterator<String> itr = lis.iterator();
while(itr.hasNext()) {
String next = itr.next();
//work with next
}
For Java 8:
List<String> lis = new ArrayList<>(Arrays.asList(arr));
lis.stream().forEach((s) -> {
//work with s
});
Both of which are silly and pointless considering you can very easily just do what you described in the OP. for
loops are an integral part of programming concepts, you can't really just avoid them.
Upvotes: 3