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

Prodentim Probiotics Specially Designed For The Health Of Your Teeth And Gums

Instant Grammar Checker - Correct all grammar errors and enhance your writing

Teach Your Child To Read

Powerful WordPress hosting for WordPress professionals

Disclosure: My content contains affiliate links.

31,109 questions

40,780 answers

573 users

How to get non repeated strings from ArrayList in Java

2 Answers

0 votes
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

public class MyClass {
    public static Set getNonRepeatedStrings(ArrayList<String> words) {
        Set<String> nonRepeating = new HashSet<String>();
        Set<String> repeating = new HashSet<String>();
    
        for (String s : words) {
            if (!repeating.contains(s)) {
                if (nonRepeating.contains(s)) {
                    repeating.add(s);
                    nonRepeating.remove(s);
                } else {
                    nonRepeating.add(s);
                }
            }
        }
        
        return nonRepeating;
    }
    public static void main(String args[]) {
        
        ArrayList<String> al = new ArrayList<String>(); 
   
        al.add("java"); 
        al.add("c++"); 
        al.add("c"); 
        al.add("javascript"); 
        al.add("c#");  
        al.add("c");  
        al.add("c");  
        al.add("php"); 
        al.add("php"); 
        al.add("javascript"); 

        System.out.println(getNonRepeatedStrings(al));
    }
}





/*
run:

[c#, c++, java]

*/

 





answered Dec 31, 2021 by avibootz
0 votes
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
 
public class MyClass {
    public static int countNonRepeatedStrings(ArrayList<String> words) {
        Set<String> set = new HashSet<>();
        Set<String> repeated = new HashSet<>();
        
        for (String s : words) {
            if(!set.add(s)) {
               repeated.add(s);
            }
        }

        return set.size() - repeated.size();
    }
    public static void main(String args[]) {
         
        ArrayList<String> al = new ArrayList<String>(); 
    
        al.add("java"); 
        al.add("c++"); 
        al.add("c"); 
        al.add("javascript"); 
        al.add("c#");  
        al.add("c");  
        al.add("c");  
        al.add("php"); 
        al.add("php"); 
        al.add("javascript"); 
 
        System.out.println(countNonRepeatedStrings(al));
    }
}
 
 
 
 
 
/*
run:
 
3
 
*/

 





answered Dec 31, 2021 by avibootz

Related questions

1 answer 52 views
1 answer 42 views
1 answer 67 views
1 answer 26 views
1 answer 62 views
...