Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Way of Adding in Elements

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.

like image 723
Michael Avatar asked Oct 08 '15 02:10

Michael


People also ask

How do I add elements to an existing list in Java?

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 .

How do I add two numbers in Java 8?

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.


1 Answers

One solution is

List<Integer> list = IntStream.range(0, 100).boxed().collect(Collectors.toCollection(ArrayList::new));

The steps:

  1. IntStream.range(0, 100) is a stream of 100 primitive ints.
  2. boxed() turns this into a stream of Integer objects. This is necessary to put the numbers into a Collection.
  3. 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.
like image 156
Paul Boddington Avatar answered Oct 03 '22 16:10

Paul Boddington