3

I want to find the average area of a few rectangles using aggregate operations in Java 8.

Rectangle[] rects = new Rectangle[]{
    new Rectangle(5, 10, 20, 30),
    new Rectangle(10, 20, 30, 40),
    new Rectangle(20, 30, 5, 15)
};

System.out.println("Average area: "
    + Arrays.asList(rects)
    .parallelStream()
    .map((RectangularShape r) -> (r.getWidth() * r.getHeight()))
    .collect(Collectors.averagingDouble(o -> o)));
// I don't like this "o -> o"
System.out.println("Expected: 625");

However, I find the o -> o required by averagingDouble kind of silly. Is there a more intuitive replacement for this lambda (maybe even a stock identity lambda somewhere)?

1
  • 1
    FYI, o -> o is not exactly the identity here -- it is an unboxing function, actually equivalent to Double::doubleValue. Commented Apr 16, 2014 at 4:19

3 Answers 3

9

No need:

System.out.println("Average area: "
     + Arrays.asList(rects)
       .parallelStream()
       .mapToDouble((RectangularShape r) -> (r.getWidth() * r.getHeight()))
       .average();

(Also, you may find Stream.of(rects).parallel()) preferable to Arrays.asList(rects).parallelStream().)

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

1 Comment

.getAsDouble() if you want to get the double value in the Optional (if there is)
3

There are identity() methods in java.util.function.X where X = Function<T,R>, UnaryOperator<T>, IntUnaryOperator, LongUnaryOperator, DoubleUnaryOperator. The one in Function<T,R> uses T. So it looks like DoubleUnaryOperator::identity should work, although o -> o is a lot less typing. (Then again, o -> o looks more like an emoticon of some kind than an expression.......)

Comments

2

In addition to the answer from @Louis, you might also want to add an area() method in Rectangle class, and then pass a method reference to mapToDouble() method:

System.out.println("Average area: "
            + Arrays.asList(rects)
            .parallelStream()
            .mapToDouble(Rectangle::area)
            .average());

Comments

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.