简体   繁体   中英

How to get specific values of objects inside an arraylist of the objects

I have created an ArrayList of Shape s, a class I created. The ArrayList contains different kinds of shapes. I also created some classes of other shapes (circle, rectangle, etc).

I used scanner so a user can type width, height, etc., of a shape he chose and that got saved inside the arraylist which contains all the shapes he creates.

How can I get the width for example, of all the shapes? I found solutions with hashMaps but is there a simpler solution?

I need to do arithmetic actions with them.

With Java 8 you can use streams

int allShapeWidths = list.stream().mapToInt(Shape::getWidth).sum();

Assuming there is a getWidth() method in Shape (is Shape an interface?)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM