Reputation: 845
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.
Upvotes: 2
Views: 23371
Reputation: 5649
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");
}
}
Upvotes: 3
Reputation: 26961
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
}
Upvotes: 3
Reputation: 16938
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;
}
}
Upvotes: 14
Reputation: 109
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");
}
}
Upvotes: 1
Reputation: 436
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;
}
Upvotes: 2