Reputation: 971
I have the below snippet.I need to find out if there is any key in the map with pattern searching with discount.Help appreciate.
public class MapStringSearch {
public static void main(String[] args) {
Map test = new HashMap();
test.put("discount.1", 1);
test.put("discount.2", 2);
test.put("discount.3", 3);
test.put("voucher.4", 4);
}
}
Upvotes: 0
Views: 91
Reputation: 2189
I would use SortedMap instead of HashMap and check if tailMap("discount").firstKey().stratsWith("discount")
Upvotes: 0
Reputation: 8106
Iterator it = test.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey().toLowerCase().contains("YourString"))
}
Upvotes: 1
Reputation: 1741
I tend to do this way:
discount.put("1", 1);
discount.put("2", 2);
discount.put("3", 3);
test.put("discounts", discount);
So to find discounts:
test.get("discounts");
And after of this you can iterate with keyset (or entryset) or find concrete discounts with get...
You can iterate the keyset, sure, but honestly; I would redefine de data scheme of my application in order to not have "something.[0-9]" elements in a hashmap.
Upvotes: 0
Reputation: 1300
One of the way is :
for ( String key : test.keySet() ) {
if(key.contains("discount"))
// do something...
else
// do something...
}
Upvotes: 1