如何在 Java 中创建多个整数和一个输入整数的'best fit'比较?



我有3个房间(未来可能会更改为更多房间,但这无关紧要(,所有房间都有不同数量的座位(假设这些是"房间"对象(:

座位
房间
1 10
2 20
3 30

您可以执行类似的操作

import java.util.ArrayList;
import java.util.Comparator;
public class Main {
public static void main(String[] args) {
new Main().test();
}
void test() {
int inputValue = 22;
ArrayList<Room> rooms = new ArrayList<Room>(); // where each room is already in the array list identified by
rooms.add(new Room(10, 1));
rooms.add(new Room(20, 2));
rooms.add(new Room(30, 3));
Integer currentDifference = null;
Room roomWithMinimalDifference = null;
for (Room room : rooms) {
int difference = room.getRoomSeats() - inputValue;
System.out.println("room "+room.getRoomNumber()+" difference "+difference);
boolean roomFitsEnteredSeats = difference >= 0; //check if room fits the entered value
if(roomFitsEnteredSeats) {
if (currentDifference == null || difference < currentDifference) {
currentDifference = difference;
roomWithMinimalDifference = room;
}
}
}
if (roomWithMinimalDifference != null) {
System.out.println("found room" + roomWithMinimalDifference.getRoomNumber() + " seats "
+ roomWithMinimalDifference.roomSeats);
} else {
System.out.println("no room was found");
}
System.out.println("-----------------------");
//========== or use this with java >= 8
Room bestMatchingRoom = rooms.stream()
.sorted(Comparator.comparingInt(Room::getRoomSeats))
.filter(r -> r.getRoomSeats() >= inputValue)
.findFirst()
.orElse(null);
if (bestMatchingRoom != null) {
System.out.println("found room" + roomWithMinimalDifference.getRoomNumber() + " seats "
+ roomWithMinimalDifference.roomSeats);
} else {
System.out.println("no room was found");
}
}
class Room {
int roomSeats;
int roomNumber;
public Room(int roomSeats, int roomNumber) {
super();
this.roomSeats = roomSeats;
this.roomNumber = roomNumber;
}
public int getRoomSeats() {
return roomSeats;
}
public void setRoomSeats(int roomSeats) {
this.roomSeats = roomSeats;
}
public int getRoomNumber() {
return roomNumber;
}
public void setRoomNumber(int roomNumber) {
this.roomNumber = roomNumber;
}
}
}

最新更新