Simplify comparsion with array

  • A+
Category:Languages

I got this simple code and I want to simplify the comparsion with array in while loop

int[] numbers = new int[7];      Random rand = new Random();     for(int i = 0; i < 7; i++) {                     int number = rand.nextInt(46);         while(number == numbers[0] || number == numbers[1] || number == numbers[2] || number == numbers[3] ||                 number == numbers[4] || number == numbers[5] || number == numbers[6]) {             number = rand.nextInt();         }         numbers[i] = number;     }     for(int i = 0; i < numbers.length; i++) {         System.out.println(numbers[i]);     } 

I want to find a way to simplify this part:

while(number == numbers[0] || number == numbers[1] || number == numbers[2] || number == numbers[3] ||                 number == numbers[4] || number == numbers[5] || number == numbers[6]) 

How can I do that?


A simple solution to this would be to use Java 8 streams.
With streams it looks like this:

int[] numbers = new Random().ints(1, 46).distinct().limit(6).toArray(); 

Thanks Elliot, I failed to recognice that the number 0 would not be choosen as all ints are 0 at the beginning.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: