Java Program to Calculate Total Income from a Collection of Room Objects

import java.util.*;

class Main {

    public static void main(String[] args) {

       Room a = new Room("Delux", "enSuite", 4, 550);

       Room b = new Room("Single", "Single", 1, 150);

       Room c = new Room("Double", "Double", 2, 250);

       Room d = new Room("Premier", "Premier", 4, 550);

       Collection<Room> rooms = List.of(a, b, c, d);

       System.out.println(calculateTotalIncome(rooms));

    }

    static double calculateTotalIncome(Collection<Room> rooms) {

        return rooms.stream()

        .mapToDouble(r -> r.getRate())   // .mapToDouble(Room::getRate)

        .sum();

    }

}

class Room {

    String name;

    String type;

    int capacity;

    double rate;

   Room(String name,

    String type,

    int capacity,

    double rate) {

        this.name = name;

        this.type = type;

        this.capacity = capacity;

        this.rate = rate;

    }

    

    public double getRate() {

        return this.rate;

    }

    

}


Output: 1500.0


package com.linkedin.collections;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

public class RoomService {

// 1. Declare a Collection to store Room Inventory
Set<Room> rooms;
public RoomService() {

// 2. Initialize Collection and assign it to the Room Inventory
rooms = new HashSet<>();
}

public Collection<Room> getInventory(){

// 3. Return the Room Inventory

return new HashSet<>(rooms);
}

public void createRoom(String name, String type, int capacity, double rate) {

// 4. Add a new Room to the Room Inventory using the provided parameters
rooms.add(new Room(name, type, capacity,rate));
}

public void createRooms(Room[] rooms) {

// 5. Add the Rooms provided in the Array to the Room Inventory
this.rooms.addAll(Arrays.asList(rooms));
}

public void removeRoom(Room room) {

// 6. Remove the provided Room from the Room Inventory
rooms.remove(room);
}

// checks for a room object
public boolean hasRoom(Room room) {
if (rooms.contains(room))
return true;
return false;
}

// convert collection into arrays
public Room[] asArray() {
return rooms.toArray(new Room[0]);
}

// filter based on room type
public Collection<Room> getByType(String type) {
Set<Room> rm = new HashSet<>(rooms);
rm.removeIf(r -> !r.getType().equals(type));
return rm;
}
}

Comments

Popular posts from this blog

Transform values with a stream

Collections Framework

Inspect a collection