-3
import java.util.ArrayList;
import java.util.Arrays;

public class Test20{

  public static void main(String args[]){
    String str="Hello java Hello python Hello testing Hello java";
    ArrayList<String> list=new ArrayList<String>();
    String s[]=str.split(" ");

    String p=s[0];
    list.add(p);

    for(int i=1;i<s.length;i++){

      if(!(p==s[i])){
        list.add(s[i]);
      }
      p=s[i];
    }//i

    for(int i=0;i<list.size();i++){
      System.out.println(list.get(i));
    }
  }
}

I want to get this result:

Hello 
java
python
testing
dokgu
  • 4,957
  • 3
  • 39
  • 77
  • Remember that you cannot use `==` to compare Strings in Java. You must use `.equals()`. – D M Mar 14 '17 at 18:35
  • This is nothing really important but just something to read on: http://stackoverflow.com/questions/129178/difference-between-int-array-and-int-array – dokgu Mar 14 '17 at 18:42
  • Why not just implement a `Set` interface? Eliminating duplicates comes for pretty much free. – seeker Mar 14 '17 at 18:44

7 Answers7

1

You can just use the contains method of the ArrayList.

for (int i = 1; i < s.length; i++) {
    if (!(list.contains(s[i]))) {
        list.add(s[i]);
    }
}

Edit: And there is no need to do a special treatment for the first word. You can just start the for loop at index 0 and leave out the two lines above the loop.

SilverNak
  • 3,283
  • 4
  • 28
  • 44
1

Lists (including ArrayList) allow duplicates.

To avoid them you can either use the contains method to check before adding...

if (!list.contains(s[i])) {
  list.add(s[i]);
}

...or use instead a Set (such as HashSet), which implicitly discards duplicate entries.

rrobby86
  • 1,356
  • 9
  • 14
1

Here is my solution. Use a Set and let Java do all the work for you.

public static void main(String args[]){

    String str="Hello java Hello python Hello testing Hello java";
    Set<String> myset=new HashSet<>();
    String s[]=str.split(" ");

    for(int i=1;i<s.length;i++){

            myset.add(s[i]);

     }

     for (String sss: myset){

        System.out.println(sss);

    }
}

}
CocoNess
  • 4,213
  • 4
  • 26
  • 43
0

Logic is wrong in the solution. You are just comparing the words next to each other. Instead, you need to check does it present in the list or You can just use HashSet to get unique.

String s[] = str.split(" "); java.util.Set result = new java.util.HashSet(java.util.Arrays.asList(s)); System.out.println(result);

Abhilash
  • 196
  • 11
0

If you want to use your own implementation (the ones provided are a bit cleaner) and for your example to print the unique words.

you just have to remove this line:

for(int i=1;i<s.length;i++){

      if(!(p==s[i])){
        list.add(s[i]);
      }
      p=s[i]; // REMOVE 
    }//i

if you keep changing p, which in your code is Hello, the words that always repeats, the check will never work. This will not work to find duplicates in all strings, just your example string.

Eddie Martinez
  • 13,582
  • 13
  • 81
  • 106
0
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringWordUnique {

  static void uniqueWord(String str) {

        Pattern p=Pattern.compile("[a-zA-Z]+");
        Matcher m=p.matcher(str);
        HashMap<String,Integer> hm=new HashMap<String, Integer>();

        while(m.find()) {
            String word=m.group();

            if(!hm.containsKey(word))
                hm.put(word, 1);
            else
                hm.put(word, hm.get(word)+1);

        }

        Set<String> s=hm.keySet();
        Iterator<String> itr=s.iterator();

        while(itr.hasNext()) {

            String w=itr.next();

            if(hm.get(w)==1)
                System.out.println(w);
        }
    }

   public static void main(String[] args) {
        String sts="Java is great. String is also great. Boot also great";
        uniqueWord(sts);
   }

}
adiga
  • 34,372
  • 9
  • 61
  • 83
  • 2
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – adiga Apr 02 '19 at 06:36
0

You can also do it with LinkedHashMap. At the end it will give you everysingle Unique words along with occurrence of words.
public static void main(String[] args) {

    String[] str = { "acorns", "apple", "banana", "acorns", "people", "acorns" };

or convert string into String array

    Map<String,Integer> map = new LinkedHashMap<String,Integer>();

    for(String a: str)
    {
        if(!map.containsKey(a))
        {
            map.put(a,1);
        }
        else
        {
            map.put(a,map.get(a)+1);
        }
    }

    System.out.println(map);

}

console result: {acorns=3, apple=1, banana=1, people=1}

Mike ASP
  • 2,013
  • 2
  • 17
  • 24