Reputation: 1
Map<String, Integer> successors = new HashMap <String, Integer> ();
// I have added some elements into the successors.
Collection<Integer> uniqueValues = successors.values();
Is there a way for me to find out in java if uniqueValues can show me that all the values in it are the same?
I planned on using the if(uniqueValues.contains(1))
statement. But I just could not figure it out. Since this statement will say true if 1 is present and other values different from 1 are also present. I just want it to return true if 1 is the only value in the collections.
eg; {1,1,1,1,1,1,1,1,1,1,1,1,1} should return true.
But {1,2,1,3,1,4,2,4,22,1,1,1,4} should return false.
Some code along the lines of "Contains if and only if."
This will be of great help. Thanks in advance.
Upvotes: 0
Views: 4718
Reputation: 27526
Some sort of Set
sounds like easiest solution
if(new HashSet<Integer>(successors.values)).size() == 1)
Because Set
can contain only unique values, logical consequence of having input collection with same values is the Set
of size one. Or you can of course introduce you own util method which will check this condition.
Upvotes: 1
Reputation: 201497
Well, you could do something like this (inefficiently),
boolean uniqueValues = new HashSet<Integer>(successors.values()).size() == 1;
Since that will check every value every time, a more efficient approach might be,
boolean uniqueValues = true;
Collection<Integer> values = successors.values();
Iterator<Integer> iter = values.iterator();
if (iter.hasNext()) {
int t = iter.next();
while (iter.hasNext()) {
int i = iter.next();
if (t != i) {
// stop if we find a different value
uniqueValues = false;
break;
}
}
}
Upvotes: 1
Reputation: 16152
Do it the CPU-clock-wasting way:
if(new HashSet(successors.values()).size()>1) {...}
Upvotes: 2