【发布时间】:2021-11-17 06:52:39
【问题描述】:
以下是我想要实现的目标。
"timezones": [
{
"name" : "America/New_York",
"label" : "US Eastern Time"
},
{
"name" : "America/Chicago",
"label" : "US Central Time"
},
{
"name" : "America/Denver",
"label" : "US Mountain Time"
},
{
"name" : "America/Los_Angeles",
"label" : "US Pacific Time"
},
]
下面是我的代码 sn-p。
Map<String,String> tz = new HashMap<>();
tz.put("America/New_York", "US Eastern Time");
tz.put("America/Chicago", "US Central Time");
tz.put("America/Denver", "US Mountain Time");
tz.put("America/Los_Angeles", "US Pacific Time");
List<Timezone> timezoneList = new ArrayList<>();
for (String key : tz.keySet()) {
Timezone timezone = new Timezone();
String value = tz.get(key);
timezone.setName(key);
timezone.setLabel(value);
timezoneList.add(timezone);
}
在这里,我基于键集迭代映射,然后从中获取值,然后创建一个对象并将其添加到列表中。这看起来像很多过程。
有没有更好的方法来做到这一点?
【问题讨论】:
-
我会迭代
tz.entrySet以避免不必要的密钥查找。我还会在 ArrayList 上设置初始容量。但除此之外,没关系。
标签: java spring-boot performance collections java-stream