Find numbers which begins with a given number in a Map in Java
Find numbers which begins with a given number in a Map in Java
I'd like to count all keys in a HashMap which begin with a given number.
The size of each key is not always the same.
Example:
given number(long):
long l = 9988776655
find the keys (long) which begin with that number like:
9988776655xxxxxxxxxxxxxxx
in which x stands for any integer.
How do I approach this problem? Since the length of the keys is not always the same I cannot do it with multiple modulo operations. (or can I?)
String.valueOf(veryLongNumber).startsWith(String.valueOf(smallerNumber))
Thanks for the quick answer!
– notsosmart.nk
Jun 29 at 11:13
3 Answers
3
I'd just convert the keys to strings:
public static long keysStartingWith(Map<Long, ?> map, long toSearch) {
String searchStr = String.valueOf(toSearch);
return map.keySet().stream().filter(k -> k.toString().startsWith(searchStr)).count();
}
You could also use an intermediate
.map(Object::toString)
but this is likely opinion based. Else, good answer!– Lino
Jun 29 at 11:15
.map(Object::toString)
Try converting the long l
and the keys to strings. Then compare the beginning of the strings. Something like this:
l
long l = 1234L;
Map<Long, Object> hashMap = new HashMap<>();
hashMap.put(1234567L, 1);
hashMap.put(1334567L, 2);
String longString = ""+l;
for(Map.Entry entry: hashMap.entrySet()) {
String keyString = ""+entry.getKey();
if(keyString.startsWith(longString)) {
System.out.println(entry.getValue());
}
}
the constructor call
new String();
should not be used– Lino
Jun 29 at 11:21
new String();
I agree. I wrote this out as an example for an approach, though it is far from being the best
– SelketDaly
Jun 29 at 11:23
Also instead of
"" + somevalue
always prefer ? String.valueOf(somevalue)
– Lino
Jun 29 at 11:25
"" + somevalue
String.valueOf(somevalue)
and BTW that is not casting - its creating a new String (or converting into a String)
– Carlos Heuberger
Jun 29 at 11:27
You could implement a general method, like this:
public static int numberOfStartsWith(Map mp, String start) {
int count = 0;
for (String key : map.keySet()) {
if (key.startsWith(start) count++;
}
return count;
}
and overload it, like this:
public static int numberOfStartsWith(Map mp, int start) {
return MyClass.numberOfStartsWith(mp, String.valueOf(start));
}
and
public static int numberOfStartsWith(Map mp, long start) {
return MyClass.numberOfStartsWith(mp, String.valueOf(start));
}
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
String.valueOf(veryLongNumber).startsWith(String.valueOf(smallerNumber))
– Lino
Jun 29 at 11:10