Java-创建对象列表



我正在创建一个函数,用于存储带有代码、名称和标志的国家列表(Image byte[](。

大约有250个国家,尽管我的方法只运行一次,但它似乎效率很低。

这是一个Maven Spring项目,图像是从/src/main/resources/images/flags加载的

private void defaultCountries() throws IOException {
List<Country> countries = new ArrayList<>();
countries.add(new Country("AF", "Afghanistan", Files.readAllBytes(Paths.get("/images/flags/af.png"))));
... // All 250 countries
}

我正在手动复制此处的信息https://github.com/yusufshakeel/mysql-country-with-flag

有人能帮我改进一下吗?

感谢

您的应用程序几乎肯定是"IO绑定"的,这意味着文件IO(输入/输出(的速度最慢。你能做的只有这么多,但至少有一件事:

我建议你把所有的国旗都放在一个拉链里(也许是未压缩的(。

文件IO时间的一个重要部分是从一个文件切换到另一个文件的操作系统开销。通过将所有内容组装到一个文件中,可以完全消除这种开销。然后,你可以阅读拉链,取出构建图像所需的各个部分。Zip库具有访问其中文件的功能,Java内置的Zip处理也不例外。每个zip条目都有一个名称和一个注释,因此您甚至可以将所有信息嵌入条目中,并将它们转换为一个小数据库。

我强烈建议不要将所有常量硬编码到源中,而只从同样硬编码的路径中读取图像。它可能适用于此任务。你的老师甚至可以接受。如果你想成为一名专业程序员,这是一个非常糟糕的习惯。

我会使用链接的哈希图作为容器和java.util.Locale来获取有关国家的信息:

private HashMap<String,Country> defaultCountries() {
return countriesWithFlags().collect(
LinkedHashMap::new,
(map,c) ->  {try {
map.put(c[0], new Country(c[0], c[1], Files.readAllBytes(Paths.get(c[2]))));
} catch (IOException ignore) {}},
LinkedHashMap::putAll
);
}
private Stream<String[]> countriesWithFlags() {
return Arrays.stream(Locale.getISOCountries()).map(iso -> new Locale("", iso))
.map(l -> new String[]{
l.getCountry(),
l.getDisplayCountry(),
String.format("/images/flags/%s.png", l.getDisplayCountry().toLowerCase())
});
}

带标志国家的单元测试:

package example;
import org.junit.Test;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.*;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
public class ContryCodesTest {
final static Logger LOGGER = Logger.getLogger(ContryCodesTest.class.getName());
public static class Country{
public Country(String iso, String name, byte[] image) {
// FIXME
}
}
private HashMap<String,Country> defaultCountries() {
return countriesWithFlags().collect(
LinkedHashMap::new,
(map,c) ->  {try {
map.put(c[0], new Country(c[0], c[1], Files.readAllBytes(Paths.get(c[2]))));
} catch (IOException ignore) {}},
LinkedHashMap::putAll
);
}
private Stream<String[]> countriesWithFlags() {
return Arrays.stream(Locale.getISOCountries()).map(iso -> new Locale("", iso))
.map(l -> new String[]{
l.getCountry(),
l.getDisplayCountry(),
String.format("/images/flags/%s.png", l.getDisplayCountry().toLowerCase())
});
}
@Test public void test() {
List<String[]> cwfs = countriesWithFlags().collect(Collectors.toList());
assertThat(cwfs, hasSize(250));
assertThat(cwfs.get(cwfs.size()-1)[2], equalTo("/images/flags/zimbabwe.png"));
}
}

最新更新