Connorelsea
Connorelsea

Reputation: 2438

How to apply functional concepts to traditionally procedural algorithms in Java 8?

After learning about lambdas in Java 8, I have been trying to think more functionally.

For example, in this algorithm I loop through an array to see which GraphicsDevice in the array matches the GraphicsDevice that is currently in use. It sets a value of the non-matching elements to false, and a value of the matching element to true.

How would I express this functionally? Or, are some things better expressed proceduraly? The method I came up with 1) doesn't work because forEach returns void, and even if it did work, it feels unnatural compared to the enhanced for loop being used in my "procedural version" of the algorithm.

public void findCurrentMonitor() {

    GraphicsDevice current = frame.getGraphicsConfiguration().getDevice();

    // Procedural version
    for (Monitor m : monitors)
        if (m.getDevice() == current) m.setCurrent(true);
        else m.setCurrent(false);

    // Functional version
    monitors.stream()
    //  .forEach(a -> a.setCurrent(false)) # Impossible. Returns void.
        .filter (a -> a.getDevice() == current)
        .forEach(a -> a.setCurrent(true));
}

Upvotes: 2

Views: 116

Answers (1)

Jatin
Jatin

Reputation: 31734

Well from pure functional programming perspective, Monitor should be immutable. You could do something like:

Stream<Monitor> stream = monitors.stream().map(x -> new Monitor(m.getDevice(), m.getDevice()==current));

In case, you wish to mutate the same monitors, why not just:

monitors.stream().forEach(a -> a.setCurrent(a.getDevice() == current));

Upvotes: 3

Related Questions