Came across the following code today, it converts the input seconds in Long to a format like 2days, 3hours, 1min, 5s. My problem with this is the use of final long[] secondsCpy = { seconds };. Any variable inside a lambda has to be final or effectively final, so, using an array variable is kind of a hack. Is there a better way to do this?
private static final LinkedHashMap<String, Long> readableTimeFormatMap = new LinkedHashMap<String, Long>() {
{
put("day", TimeUnit.DAYS.toSeconds(1));
put("hr", TimeUnit.HOURS.toSeconds(1));
put("min", TimeUnit.MINUTES.toSeconds(1));
put("sec", TimeUnit.SECONDS.toSeconds(1));
}
};
public static String getReadableTime(final long seconds) {
final StringJoiner readableTime = new StringJoiner(" ");
final long[] secondsCpy = { seconds };
readableTimeFormatMap.forEach((displayString, divider) -> {
readableTime.add(getReadableTimeUnit(displayString, secondsCpy[0] / divider));
secondsCpy[0] = secondsCpy[0] % divider;
});
return readableTime.toString().trim();
}
mapandcollect, instead of usingforeach--> no need of any final variable this way!