1

How can I reach into the condition ?

// The Strings of the list below can have the edge spaces.
List<String> list = Arrays.asList("Mango", " Apple", " Banana ", " Blackberry");
    String banana = "Banana"; // with no edge spaces
    if (list.contains(banana)) {
        System.out.println("Yes it is listed"); // How can I print this line ?
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Mr. Mak
  • 837
  • 1
  • 11
  • 25

3 Answers3

3

There are two approaches:

  1. Remove the spaces (once!) before / while you create the list. This is probably the best approach, unless you have a good reason to keep the spaces.
  2. Do the search with an explicit loop, using trim() to remove spaces before testing; e.g.

      for (String s : list) {
          if (s.trim().equals("banana")) {
               System.out.println("Yes it is listed");
               break;
          }
      }
    

    The problem with this approach is that you repeat the trimming work each time you search the list.


I would expect no loop. Is there anything to ignore the edge spaces.

Well, you can implement this with Java 8 streams (read @javaguy's answer again!), but there will be a loop under the covers, and it will most likely be slower than using an explicit loop.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
2

You need to use String class's trim() method to trim the leading or trailing spaces.

Without using Java8:

for(String fruit : list) {
      if(fruit.trim().equals(banana)) {
         System.out.println("Yes it is listed"); 
        }
}

with Java8 streams (iterates internally):

    boolean containsBanana = list.stream().
                 anyMatch( (String fruit) ->fruit.trim().equals(banana) );
            if(containsBanana) {
                 System.out.println("Yes it is listed"); 
            }

Please refer the String API trim() below for more details:

public String trim() - Returns a string whose value is this string, with any leading and trailing whitespace removed.

https://docs.oracle.com/javase/8/docs/api/java/lang/String.html

Vasu
  • 21,832
  • 11
  • 51
  • 67
1

Try trim() which returns a copy of the string, with leading and trailing whitespace omitted.

for (String str : list) {
        if(str.trim().equals(banana))
            System.out.println("Finally Yes it is listed");
}
mazhar islam
  • 5,561
  • 3
  • 20
  • 41