How to product (multiply) all distinct (non-repeating) elements in a given array with Java

1 Answer

0 votes
import java.util.HashSet;
 
public class MyClass {
    public static int printAllUniqueElements(int [] arr) {
        HashSet<Integer> hashSet = new HashSet<>();
        int product = 1;
        for (int i = 0; i < arr.length ; i++) {
            if (!hashSet.contains(arr[i])){
                product *= arr[i];
                hashSet.add(arr[i]);
            }
        }
        
        return product;
    }
    public static void main(String args[]) {
        int [] arr = {1, 4, 8, 8, 8, 1, 1, 1, 1, 7, 9 ,9, 5, 3};
       
        System.out.print(printAllUniqueElements(arr)); // 1 4 8 7 9 5 3 
     }
}
 
 
 
    
/*
run:
           
30240
           
*/

 



answered Dec 4, 2021 by avibootz
...