Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

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

2 Answers

0 votes
import java.util.Set; 
import java.util.Arrays; 
import java.util.HashSet; 
 
public class MyClass {
     public static int sumDistinctElements(Integer[] arr) {
        Set<Integer> set = new HashSet(Arrays.asList(arr));
   
        int sum = 0;
        for (Integer n : set) {
            sum += n;
        }
         
        return sum;
    }
    public static void main(String args[]) {
        Integer arr[] = {5, 2, 1, 3, 7, 1, 5, 9, 3, 3, 3, 2, 2};
   
        System.out.println(sumDistinctElements(arr)); // 5 + 2 + 1 + 3 + 7 + 9
    }
}
   
   
   
   
/*
run:
   
27
   
*/

 



answered Dec 7, 2021 by avibootz
edited May 3, 2024 by avibootz
0 votes
import java.util.HashSet;
  
public class MyClass {
    public static int sumDistinctElements(int [] arr) {
        HashSet<Integer> hashSet = new HashSet<>();
        int sum = 0;
        for (int i = 0; i < arr.length ; i++) {
            if (!hashSet.contains(arr[i])){
                sum += arr[i];
                hashSet.add(arr[i]);
            }
        }
         
        return sum;
    }
    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(sumDistinctElements(arr)); // 1 + 4 + 8 + 7 + 9 + 5 + 3 
     }
}
  
  
  
     
/*
run:
            
37
            
*/

 



answered May 3, 2024 by avibootz
...