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.
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];
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.
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 .
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.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