Advertisement
dburyak

java 8 red rectangles

Apr 19th, 2021
1,006
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.86 KB | None | 0 0
  1. public class Rectangle {
  2.     private int bLength;
  3.     private int aLength;
  4.     private int number;
  5.     private String color;
  6.     private int area;
  7.  
  8.     public Rectangle(int aLength, int bLength, int number, String color) {
  9.         // TODO: add validations here (non-negative, etc.)
  10.         this.aLength = aLength;
  11.         this.bLength = bLength;
  12.         this.number = number;
  13.         this.color = Objects.requireNonNull(color);
  14.         this.area = -1;
  15.     }
  16.  
  17.     public int getbLength() {
  18.         return bLength;
  19.     }
  20.  
  21.     public int getaLength() {
  22.         return aLength;
  23.     }
  24.  
  25.     public int getNumber() {
  26.         return number;
  27.     }
  28.  
  29.     public String getColor() {
  30.         return color;
  31.     }
  32.  
  33.     public int getArea() {
  34.         if (area != -1) {
  35.             area = aLength * bLength;
  36.         }
  37.         return area;
  38.     }
  39. }
  40.  
  41.  
  42. public class App {
  43.     public static void main(String[] args) {
  44.         Map<String, Rectangle> rectangles = Map.of(
  45.                 "one",   new Rectangle(10, 20, 0, "green"),
  46.                 "two",   new Rectangle(15, 25, 1, "red"),
  47.                 "three", new Rectangle(20, 30, 2, "yellow"),
  48.                 "four",  new Rectangle(25, 35, 3, "red"),
  49.                 "five",  new Rectangle(30, 40, 4, "white"),
  50.                 "six",   new Rectangle(35, 45, 5, "red")
  51.         );
  52.  
  53.         var modifiedRectangles = rectangles.values().stream()
  54.                 .filter(r -> isRed(r))
  55.                 .map(r -> withChangedAValue(r))
  56.                 .collect(Collectors.toList());
  57.     }
  58.  
  59.     private static boolean isRed(Rectangle rectangle) {
  60.         return rectangle.getColor().equalsIgnoreCase("red");
  61.     }
  62.  
  63.     private static Rectangle withChangedAValue(Rectangle r) {
  64.         // do the needed change here
  65.         return new Rectangle(r.getaLength() + 100, r.getbLength(), r.getNumber(), r.getColor())
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement