Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine if numbers in an array list if divisible by the numbers in another array list?

Tags:

java

arraylist

I am trying to determine if the numbers in an array list are divisiable by all of numbers in antoher arraylist. My code below outputs all of the numbers from the listdiv list that are disible by any divisors in the listdivisor. I would like to output the values that are divisible by all divisiors in the list not any of them. For example If I have listdiv = [1,2,3,,5,8] and listdivisor= [2,4]. the expected output should be 8 , but this code outputs 2 and 8 .

Thank you !your effort will be greatly appreciated!

for (int i = 0; i < listdiv.size(); i++) {
            for (int c = 0; c < listdivisor.size(); c++) {
                if (listdiv.get(i) % listdivisor.get(c) == 0) {
                System.out.println("final results are :  " + listdiv.get(i));
                }
            }
        }
like image 840
gqli Avatar asked Feb 04 '26 07:02

gqli


1 Answers

Other way with java 8:

List<Integer> collect = listdiv.stream().filter(p ->
        listdivisor.stream().allMatch(d -> p % d == 0)
).collect(Collectors.toList());

Or better performance with parallelStream():

List<Integer> collect = listdiv.parallelStream().filter(p ->
        listdivisor.parallelStream().allMatch(d -> p % d == 0)
).collect(Collectors.toList());
like image 128
Viet Avatar answered Feb 05 '26 20:02

Viet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!