gpt4 book ai didi

java - 等于或介于两个值之间的查找值

转载 作者:行者123 更新时间:2023-12-02 03:41:57 25 4
gpt4 key购买 nike

我有一个 CSV 文件,它将区域链接到邮政编码。它看起来像这样(最低邮政编码,最高邮政编码,区域):

1600,1799,1
1800,1899,1
4300,4699,1
2820,2839,2
2850,2879,2
2930,2949,2
5600,5819,3
5850,6514,3
6516,6549,3
6800,6849,3

我需要一个根据邮政编码返回区域的函数。像这样的事情:

foo = getRegion(1600) // foo is set to 1
bar = getRegion(1642) // bar is set to 1
baz = getRegion(4351) // baz is set to 2
qux = getRegion(1211) // qux is set to null

我目前实现这一点的方式是使用HashMap。当我读取 CSV 时,我会迭代 1600 到 1799 之间的每个值,并为每个邮政编码/区域组合创建一个键值对,并对 CSV 中的每一行重复该操作。结果是一个如下所示的 HashMap:

1600,1
1601,1
1602,1
...
1799,1
1800,2
1801,2
...

这会创建一个大的HashMap,它确实有效。有没有比将这个小表分解为一个大的 HashMap 更(内存)高效的实现?

最佳答案

像下面这样的东西会有帮助 -

class ZipRange {
int start;
int end;
}

// Fill up this map parsing through csv
Map<ZipRange, Integer> zipToRegion;

int zipToSearch = 2870;

// Create method which returns integer which corresponds to region
for (ZipRange zip : zipToRegion.keySet()) {
if (zipToSearch >= zip.start && zipToSearch <= zip.end) {
return zipToRegion.get(zip);
}
}
return -1;

关于java - 等于或介于两个值之间的查找值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36739154/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com