Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to avoid loops when adding to a list?

I was wondering a code like this:

List<String> list = new ArrayList<String>(); for(CustomObject co : objects) {     list.add(co.getActualText()); } 

Can it be written differently? I mean of course at some point there will be a loop but I am wondering if there is an API usage I am ignoring

like image 767
Jim Avatar asked Mar 19 '15 22:03

Jim


People also ask

How do you avoid a loop in programming?

Another way we can avoid using imperative loops is through recursion. Recursion is simple. Have a function call itself (which creates a loop) and design an exit condition out of that loop.

How do you stop a loop in Java?

The break statement is used to terminate the loop immediately. The continue statement is used to skip the current iteration of the loop. break keyword is used to indicate break statements in java programming. continue keyword is used to indicate continue statement in java programming.

Can you use enhanced for loop on list?

Method 1-B: Enhanced for loop Each element can be accessed by iteration using an enhanced for loop. This loop was introduced in J2SE 5.0. It is an alternative approach to traverse the for a loop.

Which type of loop is most effective to iterate over a list?

Using an iterator, or using a foreach loop (which internally uses an iterator), guarantees that the most appropriate way of iterating is used, because the iterator knows about how the list is implemented and how best go from one element to the next.


1 Answers

If you use Java 8, you can take advantage of the Stream API:

List<String> list = objects.stream()                            .map(CustomObject::getActualText)                            .collect(Collectors.toList()); 
like image 149
Konstantin Yovkov Avatar answered Sep 23 '22 15:09

Konstantin Yovkov