LearnFrenzy
Sign in Take a free test

Lambda Expressions · Lambda Expressions Programs · Question 9

Traffic light state machine with lambda transitions in Java Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 9 Back to Exercise

Model a traffic light whose transitions are stored as a Map from state to UnaryOperator, with timing per state; simulate the light for 100 seconds and print each change.

Solution
Main.java
import java.util.EnumMap;
import java.util.Map;
import java.util.function.UnaryOperator;

enum Light { GREEN, YELLOW, RED }

public class Main {
    public static void main(String[] args) {
        Map<Light, UnaryOperator<Light>> next = new EnumMap<>(Light.class);
        next.put(Light.GREEN, l -> Light.YELLOW);
        next.put(Light.YELLOW, l -> Light.RED);
        next.put(Light.RED, l -> Light.GREEN);
        Map<Light, Integer> seconds = new EnumMap<>(Map.of(Light.GREEN, 30, Light.YELLOW, 5, Light.RED, 25));

        Light state = Light.RED;
        int t = 0;
        while (t < 100) {
            System.out.printf("t=%3d %s for %ds%n", t, state, seconds.get(state));
            t += seconds.get(state);
            state = next.get(state).apply(state);
        }
    }
}

Output Verified by compiling and running

t=  0 RED for 25s
t= 25 GREEN for 30s
t= 55 YELLOW for 5s
t= 60 RED for 25s
t= 85 GREEN for 30s

Transitions are data (lambdas in a map), so changing the sequence means changing the map, not the loop.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links