Is there any method in Java to init a set by step 1 or other length? -
for example, init set [1,2,3, ...,100].
usually, follows:
for(int = 1;i <= 100;i++ ){ set.add(i); }
is there method more conveniently?
such somemethod(startindex, endindex, step);
by using that, can init set [1,2,3,4,5] or [1,3,5,7,9] or others.
you can use java 8 streams.
for example :
set<integer> myset = intstream.range(1,101).boxed().collect(collectors.toset());
or odd numbers :
set<integer> myset = intstream.range(1,101).filter(i->i%2==1).boxed().collect(collectors.toset());
intstream.range
easy way obtains numbers in given range.- then can apply filters if want of numbers.
- finally can collect them collection wish.
Comments
Post a Comment