Below is what I am trying to achieve.
"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"
},
]
Below is my code snippet.
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);
}
Here I am iterating map based on keyset and then getting value from it, then creating an object and adding it to list. This looks like lot of process.
Is there any better way to do this?
CodePudding user response:
If the input data are provided as the mentioned JSON string, it would be better to implement a POJO and then deserialize that JSON as a list/array.
If the input data are provided as a map, a constructor/mapper method/builder should be implemented for
Timezone
class to convert the map entries:
Map<String,String> tz = Map.of(
"America/New_York", "US Eastern Time",
"America/Chicago", "US Central Time",
"America/Denver", "US Mountain Time",
"America/Los_Angeles", "US Pacific Time"
);
List<Timezone> timezoneList = tz.entrySet()
.stream()
.map(e -> new Timezone(e.getKey(), e.getValue())) // constructor
// .map(e -> new TimezoneBuilder().withName(e.getKey()).withLabel(e.getValue()).build()
.collect(Collectors.toList());
CodePudding user response:
Here's a 'modern' way, using streams and a record
, but what you have written is fine.
public class SO69307363 {
record TimeZone(String name, String label){};
public static void main(String[] args) {
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> timeZones = tz.entrySet().stream()
.map(e -> new TimeZone(e.getKey(), e.getValue()))
.collect(Collectors.toList());
}
}
I think that this way is easier to read and understand, simply because there is less code.
CodePudding user response:
If you use Apache commons library, then here is a one liner solution for you.
List<Timezone> collect = CollectionUtils.collect(tz.entrySet().iterator(), entry -> new Timezone(entry.getKey(), entry.getValue()), new ArrayList<>());
if you prefer to use Java-8 syntax, then follow the answer provided by tgdavies above.