2

I have an ArrayList with a set of (same) string values which I need to compare with a single String value and return true or false. Is there any way to do that in Java?

For example, say I have a <String>ArrayList with 5 values = foo, foo, foo, foo, foo (My requirement is such that all the values in the arraylist will be the SAME) and I have a String str = "foo". I need to verify that whether ALL the values in the arraylist is the SAME as the string value i.e., all the values present in the arraylist SHOULD be "foo".

I tried to google this info and all I can see is suggestions to use contains() method, in different ways, which will return true even if anyone value in the arraylist contains the specified value.

I even figured a workaround for this - Creating another arraylist with expected values and compare the two lists using equals() method and it seems to be working. I was just wondering whether there is any simple way to achieve this.

2
  • 4
    Just iterate the list and compare each item with your String. If all are equal, true, if any is not, false. Commented Aug 25, 2015 at 10:40
  • I can do that but I was looking for a single line solution, exactly like what @steffen has suggested. Commented Aug 25, 2015 at 11:31

5 Answers 5

14

That's simple with Java 8:

String str = "foo";
List<String> strings = Arrays.asList("foo", "foo", "foo", "foo", "foo");
boolean allMatch = strings.stream().allMatch(s -> s.equals(str));

For Java 7 replace the last line with:

boolean allMatch = true;
for (String string : strings) {
    if (!string.equals(str)) {
        allMatch = false;
        break;
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

For clarity maybe final String str = "foo";. And for thousand foos, a parallelStream() might be an idea.
Java 8 is rolling in. +1
@steffen Excellent! This is exactly what I'm looking for and it worked. Thank You!! Also, I'm new to java. So, It will be more helpful if you can explain what exactly this line does boolean allMatch = strings.stream().allMatch(s -> s.equals(str));
@justcurious There's tons of documentation about it out there and it's too complex to explain here. Search for Java 8 Lambdas and Streams. In short: Java 8 offers streams which are similar to Unix pipes. With streams you iterate collections and perform one or more operations. allMatch() is a short-circuiting terminal operation meaning that the iteration stops immediately after the first non-matching item is encountered and returns false. If all items match, it returns true.
Thanks a lot! This helps :)
3

If you want to know if the array contains the string use ArrayList::contains()

String s = "HI";
ArrayList<String> strings = // here you have your string

if (string.contains(s)) {
    // do your stuff
}

If you want to check if all values are same, iterate and count. If you have JAVA8 check steffen sollution.

boolean areSame = true;
for (String str : strings) {
    if (!str.equals(s)) areSame = false;
}

if (areSame) {
    // all elements are same
}

3 Comments

OP said this was not what they wanted, as it only sees if one string is equal
The problem is that he wants to check if every entry in the list is the same value.
OP said all strings in the list must be compared to be equal to the given string.
3

1) You can the pass the arraylist into a set.

2) Now you can get the size of set, if it is equal to 1 that means all elements are same.

3) Now you can use the contains on set to check if your value is present in it or not.

public static void main(String[] args){
          String toBeCompared="foo";
          List<String> list=new ArrayList<String>();
          list.add("foo");
          list.add("foo");
          list.add("foo");
          list.add("foo");
          list.add("foo");
          Set<String> set=new HashSet<String>(list);
          if(1==set.size()){
              System.out.println(set.contains(toBeCompared));
          }
          else{
             System.out.println("List has different values");
          }
    }

5 Comments

Or use Set.contains() for step 3.
Something like this? new HashSet(list).size() == 1 && str.equals(list.get(0)) - Not getting it from the set to make it single line.
@KDM - HashSet<String> or HashSet<> would be better, I believe.
@RealSkeptic not in java 8 when passing a collection. Point noted.
@RealSkeptic Thanks for your comment, edited my answer.
2

You can use this method to do that

private boolean allAreSame(ArrayList<String> stringList, String compareTo){
    for(String s:stringList){
        if(!s.equals(compareTo))
             return false;
    }
    return true;
}

4 Comments

should use !equals instead of !=
it will return the same thing, but i will fix it
FYI: == tests for reference equality (whether they are the same object). .equals() tests for value equality (whether they are logically "equal"). Consequently, if you want to test whether two strings have the same value you should use .equals(), because there're plenty of cases when == wouldn't return true for comparison.
thank you for future reference, but i have already fixed it :)
1

I would do it like this:

ArrayList<String> foos = new ArrayList<>();
String str = "foo";     
for (String string : foos) {
    if(string.equals(str)){
            System.out.println("True");
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.