Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Remove the same word from a list? | Java

I want to remove/ delete duplicate words. I tried this but it wont work.
Does someone have a solution for this?


    public static void main(String[] args) {
        List<String> words = sw("This is is an example");
        System.out.println(words); // => [an, example, is, This]
    }
    public static List<String> sw(String s) {
    List<String> words = new ArrayList<String>(Arrays.asList(s.trim().split(" +")));
    int size = words.size();
        for(int i = 0;i < size;i++) {
            for(int k = i+1;k < size;k++) { 
                if(size == 1) {
                    break;
                }
                if(k < size -1 && words.get(i).equals(words.get(k))) {  
                    words.remove(k);
                    k = k -1;
            }   if(size == 1) {
                break;
            }
                
         }
    }
        Collections.sort(words);
        return words;
}
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

this should be the solution 🙂

public static List<String> sw(String s) {
            List<String> words = new ArrayList<String>(Arrays.asList(s.trim().split(" +")));
            int size = words.size();
                for(int i = 0;i < size;i++) {
                    for(int k = i+1;k < size;k++) { 
                        if(k <= size -1 && words.get(i).equals(words.get(k))) {  
                        words.remove(k);
                        k--;
                        size--;
                    }   
                }
            }
            Collections.sort(words);
            return words;
        }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading