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
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.
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.
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.
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.
If you use Java 8, you can take advantage of the Stream API:
List<String> list = objects.stream() .map(CustomObject::getActualText) .collect(Collectors.toList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With