Piyush Vishwakarma
Piyush Vishwakarma

Reputation: 1826

Java Netbeans Code Transformation

I am working with Java on netbeans IDE. With the help of netbeans code transformation i have found following codes which turns out to display the same thing using different methods. Following are the codes, here a is an ArrayList.

//code 1
for(int j=0;j<a.size();j++)
{
    System.out.println(a.get(j));
}
//code 2
for (Integer a1 : a) {
System.out.println(a1);
}
//code 3
a.stream().forEach((a1) -> {
System.out.println(a1);
});
//code 4
a.stream().forEach(new Consumer<Integer>() {

        @Override
        public void accept(Integer x1) {
            System.out.println(x1);
        }
    });

For the last code, 'java.util.function.Consumer' is imported. I want to know is there any significant difference between these methods and if yes then what are they?

Upvotes: 2

Views: 104

Answers (1)

Eran
Eran

Reputation: 394146

The 3rd and 4th snippets, that create a Stream, would have some additional overhead, so they would be a little less efficient.

There's a 5th option that would be the shortest to write :

a.forEach(System.out::println)

Upvotes: 1

Related Questions