0

I have an arrayList with a bunch of strings in it. I also have another arrayList with a bunch of strings. I would like to see whether the first array list contains any string from the second arrayList and if so, just to print it out. Should be simple but it doesn't seems to work (and there are definitely strings in common).

Here is my code:

 ArrayList<String> che=new ArrayList<String>();
 for (int i = 1; i <= rsmd.getColumnCount(); i++) {
     System.out.println("COL"+rsmd.getColumnName(i));
     che.add(rsmd.getColumnName(i).trim());
 }
 String key = "";
 String keys = "";
 for (Entry<String, String> entry : map.entrySet()) {
     key = entry.getKey().replace(":","")
           .replace(">","MoreThan").replace("__","")
           .replaceAll("\\." ,"").replaceAll("\\(s\\)" ,"")
           .replaceAll(",$" ,"").replaceAll("%" ,"")
           .replaceAll("\\(" ,"").replaceAll("\\)" ,"")
           .replace("-" ,"").replace("-" ,"")
           .replace("_" ,"").replace("#" ,"")
           .replaceAll("\\/", "_").replaceAll("@", "AT")
           .replaceAll("&", "AND").replaceAll("\\?", "AND")
           .replace("≤","LessThan").replace("≥","MoreThan")
           .replaceAll("\\s" ,"").replaceAll("^,","");  
     for (String n:che){
         System.out.println("Che_String "+n);
         System.out.println("KEY_String "+key);
         if (n==key){
             System.out.println("Detected the same: "+key.trim());
         }
     }
 }

I know there are a lot of replaces and I should use StringUtils.repaceEach and I will do so but need to sort this first

The System.out.println output shows that there are several similar strings but they are not being picked up eg

Che_String Gender
KEY_String Gender

But my Detected the same: output is empty.

I've also tried che.contains(key) with the same results.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Sebastian Zeki
  • 6,690
  • 11
  • 60
  • 125

2 Answers2

2

String should be compared with the String.equals(String) method. With == you compare if it is the same object and not the same content. List.contains(Object) is using the equals() method. So this should work. Maybe you got some whitespace at the end of your text that is not visible in your test print.

Simulant
  • 19,190
  • 8
  • 63
  • 98
0

In Java 8:

che.stream().filter(n -> map.keySet().contains(n)).forEach(match -> System.out.println("Detected the same: " + match);)

Lee
  • 738
  • 3
  • 13