【问题标题】:Find numbers which begins with a given number in a Map in Java在Java中的Map中查找以给定数字开头的数字
【发布时间】:2018-06-29 11:09:40
【问题描述】:

我想计算 HashMap 中以给定数字开头的所有键。 每个键的大小并不总是相同的。 示例:

给定数字(长):

long l = 9988776655

找到以该数字开头的键(长),例如:

9988776655xxxxxxxxxxxxxxx

其中 x 代表任意整数。

我该如何解决这个问题?由于键的长度并不总是相同的,我不能用多个模运算来做到这一点。 (或者我可以吗?)

【问题讨论】:

  • String.valueOf(veryLongNumber).startsWith(String.valueOf(smallerNumber))
  • 感谢您的快速回答!

标签: java dictionary hashmap key


【解决方案1】:

我只是将键转换为字符串:

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();
}

【讨论】:

  • 您也可以使用中间的.map(Object::toString),但这可能是基于意见的。否则,很好的答案!
【解决方案2】:

尝试将长 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());
    }
}

【讨论】:

  • 不应使用构造函数调用new String();
  • 我同意。我写了这个作为一个方法的例子,虽然它远不是最好的
  • 也总是喜欢而不是"" + somevalueString.valueOf(somevalue)
  • 和 BTW 不是 casting - 它创建一个新字符串(或转换为字符串)
【解决方案3】:

你可以实现一个通用的方法,像这样:

public static int numberOfStartsWith(Map mp, String start) {
    int count = 0;
    for (String key : map.keySet()) {
        if (key.startsWith(start) count++;
    }
    return count;
}

然后重载它,像这样:

public static int numberOfStartsWith(Map mp, int start) {
    return MyClass.numberOfStartsWith(mp, String.valueOf(start));
}

public static int numberOfStartsWith(Map mp, long start) {
    return MyClass.numberOfStartsWith(mp, String.valueOf(start));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-15
    相关资源
    最近更新 更多