Search code examples
javastringlistarraylistlinkedhashset

How to get an Arraylist<String> after using List and LinkedHashSet to remove duplicate values from a string in Java


This is part of a homework assignment, a search engine. I am trying to make a class that removes duplicate values from string input (input will be taken from user, using a random String now for test) and stores the tokens/words into an ArrayList to compare them against a String[] of Stop Words (words to remove). I am using List and LinkedHashSet because I want to preserve the order of the words and to remove duplicates. It does remove the duplicate words and preserves order but I can't get it to store the words into an ArrayList, any ideas?

import java.util.Arrays;
import java.util.List;
import java.util.LinkedHashSet;
import java.util.Set;

public class RemoveDuplicateWord {

    public static void main(String[] args) {
        String str = "the search engine that could search";
        removeDupWord(str);
    }

    public static void removeDupWord(String str) {
        List<String> list = Arrays.asList(str.split(" "));
        Set<String> lhs = new LinkedHashSet<String>(list);

        for(String s : lhs) {
            System.out.print(s+" ");
        }
    }
}

Solution

  • I think this is what you want as i understood what u need :/ hope it works

    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.LinkedHashSet;
    import java.util.Set;
    public class RemoveDuplicateWord {
       public static void main(String[] args) {
    
            String str = "the search engine that could search";
            removeDupWord(str);
        }
    public static void removeDupWord(String str) {
        List<String> list = Arrays.asList(str.split(" "));
        Set<String> lhs = new LinkedHashSet<String>(list);
        ArrayList<String> words = new ArrayList<String>();
        for(String s : lhs) {
            words.add(s);
        }
        for(int i=0;i<words.size();i++) {
            System.out.print(words.get(i) + " ");
        }
    }
    }