java - 找到下一个最小的键(需要性能建议)

标签 java algorithm list search dictionary

我需要一些性能方面的建议。我有一个 Map<DateTime, String> .我需要类似以下方法的方法:

Map<DateTime, BigDecimal> map; // about 50 entries. Btw: Which impl to choose?

BigDecimal findNextSmaller(DateTime input) {

    DateTime tmp = null;

    for(DateTime d : map.keySet()) {
        if(tmp == null && d < input) {
            tmp = d;
        }
        if(d < input && d > tmp) {
            tmp = d;
        }
    }

    return map.get(tmp);
}

所以基本上我只是迭代我的 Map 的 keySet并尝试找到与 input 相比下一个最小的键.

这个方法将被连续调用大约 1.000.000 次:

BigDecimal sum;

List<Item> items; // about 1.000.000 Items

for(Item i : items) {
    sum = sum.add(findNextSmaller(i.getDateTime()));
}

现在我正在寻找一种让事情变得更快的方法。

我的第一个想法是制作一个 OrderedList来自 Map的键集。所以平均而言,我只需要迭代 DateTime 的一半以上秒。然后就做一个 map.get(dateTimeFromOrderedList)得到匹配值。

但这就是我能做的一切吗?

最佳答案

您可以使用具有 built-in method 的 TreeMap为此:

TreeMap<DateTime, BigDecimal> map = new TreeMap<>();
//populate the map

BigDecimal findNextSmaller(DateTime input) {
    return map.ceilingEntry(input).getValue(); //add exception checking as required
}

注意:您可能需要 ceilingEntryhigherEntry取决于你是否想要(resp.)>=> .

关于java - 找到下一个最小的键(需要性能建议),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21633384/

相关文章:

java - MidiSystem.getMidiDevice(...) 返回意外的类

java - 如何散列 2D 平面中的几何点?

无法推到列表后面

java - 以下代码的输出是什么

java - 如何通过 Maven 在 RCP 应用程序中使用 log4j?

java - 在 2 个字符串中搜索字谜的程序中出现异常

c - 提取数组中的唯一元素(来自 K 和 R C ex1-14)

algorithm - 圆圈碰撞问题

python - 无法将 'list' 对象隐式转换为 str python

list - SwiftUI - 滚动列表时 View 中的动画停止