0

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?

3
  • 1
    Why would you ever need to not use a for loop? No. Commented Apr 25, 2014 at 0:47
  • 1
    "is there any way to do this without a for loop?" how about while loop? Commented Apr 25, 2014 at 0:50
  • Assuming the answer you're looking for isn't @ImmerAllein 's "while-loop" suggestion...No. Commented Apr 25, 2014 at 0:51

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Seconded. If you think about it programmatically, regardless of structure or library, the software is going to have to iterate over the elements. A For-loop works just as well as anything else.
Note that both of these methods actually iterate through the array for you, but much less readbly and efficiently. Use a for loop.
OK that makes sense thank you guys! It just seemed kind of trivial to create a for loop that takes up several lines of code, only to to add one to a list of variables, and other things like that.
@Anubian Noob : Both methods are better than iterating via a loop. Second can also be made faster using multiple cores at the same time. So in terms of performance, although it may not seem fast now, it is suitable for performance optimizations in future.
@TanmayPatil This is one of those optimizations where it is rarely worth it... Especially for the three element array the asker provided. Still, this does answer the question very well.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.