Is there a more concise, perhaps one liner way, to write the following:
ArrayList<Integer> myList = new ArrayList<>();
for (int i = 0; i < 100; i++){
myList.add(i);
}
Using Java 8 features, and functionally insipred approaches. I'm not expecting a Haskell solution like:
ls = [1..100]
But something more elegant than the traditional imperative style.
There are two methods to add elements to the list. add(E e ) : appends the element at the end of the list. Since List supports Generics , the type of elements that can be added is determined when the list is created. add(int index , E element ) : inserts the element at the given index .
b) By Using the Sum() Method The sum() method is used to add numbers given in the arguments of the method. The sum() method is in the Integer class of Java which is in the util package. We will use the Integer. sum() function.
One solution is
List<Integer> list = IntStream.range(0, 100).boxed().collect(Collectors.toCollection(ArrayList::new));
The steps:
IntStream.range(0, 100)
is a stream of 100 primitive int
s.boxed()
turns this into a stream of Integer
objects. This is necessary to put the numbers into a Collection
.collect(Collectors.toCollection(ArrayList::new));
is how you convert a Stream
to an ArrayList
. You can replace ArrayList::new
by any supplier for a collection, and the elements will be added to that collection.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