Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want non duplicate elements from list

From following list I need only 'wow' and 'quit'.

List<String> list = new ArrayList();                
list.add("test");       
list.add("test");                   
list.add("wow");    
list.add("quit");
list.add("tree");
list.add("tree");
like image 504
user1959531 Avatar asked Jan 08 '13 22:01

user1959531


People also ask

How do you remove repetitive elements from a list?

To remove duplicates using for-loop , first you create a new empty list. Then, you iterate over the elements in the list containing duplicates and append only the first occurrence of each element in the new list. The code below shows how to use for-loop to remove duplicates from the students list.

How do you prevent duplicate elements in a set?

for the first time add SOP will return true. then for the second time of added "123", SOP will return false. With this we can understand that, if we add same value in the Set for the second time or more, then the duplicated value will be skipped.


2 Answers

you can check the frequency of an element in the Collection and rule out the elements which have frequency higher than 1.

   List<String> list = new ArrayList<String>();
    list.add("test");       
    list.add("test");                   
    list.add("wow");    
    list.add("quit");
    list.add("tree");
    list.add("tree");
    for(String s: list){
        if(Collections.frequency(list, s) == 1){
            System.out.println(s);
        }

Output:

wow
quit
like image 156
PermGenError Avatar answered Oct 14 '22 23:10

PermGenError


This snippet should leave you with a set (output) which contains only non-duplicated elements of your list.

HashSet<String> temp = new HashSet<String>();
HashSet<String> output = new HashSet<String>();

for (String element : list)
{
    if (temp.contains(element)) output.remove(element);
    else
    {
        temp.insert(element);
        output.insert(element);
    }
}

Operates in O(n*log(n)) time: one set of logarithmic operations (set lookups, inserts, etc) for each of the n elements in the list.

like image 28
Wug Avatar answered Oct 15 '22 01:10

Wug