Java 8 Way to Add Items

Is there a shorter, maybe one way liner, write the following:

ArrayList<Integer> myList = new ArrayList<>(); for (int i = 0; i < 100; i++){ myList.add(i); } 

Using Java 8 features and functionally unused approaches. I do not expect a Haskell solution, for example:

 ls = [1..100] 

But something more elegant than the traditional imperative style.

+5
source share
1 answer

One solution is

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

Stages:

  • IntStream.range(0, 100) - stream of 100 primitive int s.
  • boxed() turns this into a stream of Integer objects. This is necessary to put numbers in the Collection .
  • collect(Collectors.toCollection(ArrayList::new)); is how you convert a Stream to an ArrayList . You can replace ArrayList::new any provider for the collection, and the items will be added to this collection.
+6
source

Source: https://habr.com/ru/post/1233210/


All Articles