Reputation: 77
I want to search for particular String
elements within a Pair<String,int>
.I am using the simple equals
method to do this. Please suggest me any other useful technique for this. The String
list is having at least 10000 elements.
for (String str1 : StringList) {
for (Pair<?, ?> pair : nodeList) {
if (pair.getFirst().equals(str1)) {
// Some code here...
}
}
}
Upvotes: 0
Views: 1136
Reputation: 6730
If you want to repeatedly check if your StringList
contains a particular String
, you'd be better off using a HashSet<String>
instead.
Use the HashSet.contains() method to check if your string exists - this way, you'll get the return value immediately in O(1) time instead of having to iterate over all the elements.
Upvotes: 1
Reputation: 9559
Doing a sequential scan on >10000 records and performing a String.equals() operation will be slow. Consider using a HashMap instead, where keys are the first (string) in each pair, values are the second (integer):
Map<String, Integer> map = //... get your map
for (String str : stringList) {
Integer found = map.get(str);
if (found!=null) {
// Some code here...
}
}
Upvotes: 1
Reputation: 371
I think you shold use a HashMap
for this. It contains pairs like key->value and you can easy check existance of both with containsKey
and containsValue
methods.
Upvotes: 3
Reputation: 15990
If I understand your question correctly, you want to search for a particular Pair of Strings in a List. That particular Pair first element must match the String you are looking for, correct?
Well, if your list is not ordered in any way, you're out of luck. Go through all the elements and search for it.
If the List is ordered (in order of the first element of the Pair), then you can use a Binary Search to do it blazingly faster.
Upvotes: 0
Reputation: 73558
Use a HashSet
instead of a List. It brings the complexity down to O(n) instead of the O(n^2) you have now.
Upvotes: 0