Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any method in Java to init a set by step 1 or other length?

Tags:

java

For example, I like to init a set like [1,2,3, ...,100].

Usually, we do as follows:

for(int i = 1;i <= 100;i++ ){
    set.add(i);
}

Is there any method to do this more conveniently?

Such as someMethod(startIndex, endIndex, step);

By using that, we can easily init a set like [1,2,3,4,5] or [1,3,5,7,9] or others.

like image 600
weaver Avatar asked Jul 08 '15 07:07

weaver


People also ask

How do you initialize an array in Java with 1?

Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10];

How do you initialize an entire array with 1?

Initializer List: To initialize an array in C with the same value, the naive way is to provide an initializer list. We use this with small arrays. int num[5] = {1, 1, 1, 1, 1}; This will initialize the num array with value 1 at all index.

How do you initialize a set of values?

To initialize a Set with values, pass an iterable to the Set constructor. When an iterable is passed to the Set constructor, all elements get added to the new Set . The most common iterables to initialize a Set with are - array, string and another Set .


1 Answers

You can use Java 8 Streams.

For example :

Set<Integer> mySet = IntStream.range(1,101).boxed().collect(Collectors.toSet());

or for odd numbers only :

Set<Integer> mySet = IntStream.range(1,101).filter(i->i%2==1).boxed().collect(Collectors.toSet());
  • IntStream.range is an easy way to obtains numbers in a given range.
  • Then you can apply filters if you only want some of the numbers.
  • Finally you can collect them to any collection you wish.
like image 90
Eran Avatar answered Nov 07 '22 08:11

Eran