2

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();
    }
1
  • 3
    return any value from your lambda with a combination of map and collect, instead of using foreach --> no need of any final variable this way! Commented Apr 18, 2018 at 14:44

2 Answers 2

3

There is no much better way to do this, you can use for example AtomicLong

Sign up to request clarification or add additional context in comments.

Comments

2

Well without complicating things, you could always resort to using an enhanced for loop.

long secondsCpy = seconds;
for (Map.Entry<String, Long> entry : map.entrySet()) {
    readableTime.add(getReadableTimeUnit(entry.getKey(), secondsCpy / entry.getValue()));
    secondsCpy = secondsCpy % entry.getValue();
}

4 Comments

You don’t even need the secondsCpy, as seconds will not be used for anything else in this method.
@Holger in the question you can see that seconds is a final variable, so it is necessary to do a copy.
Yeah, we could use this too, but wanted to see if it can be done using a lambda function. Thanks!
@Kermi or you remove that final modifier. It has no practical relevance anyway (besides making a second variable necessary).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.