Java – find element or check if it exists in array / list?

I'm a novice. I really don't understand how this works

I made a list of room information:

List<Room> rooms = new ArrayList<>();

Each room stores data about its room number (integer), type (enumeration), price (double), capacity (integer) and facilities (string)

To make a long story short, my question is:

(1) How do I search this list, for example, to check if a room number '401' exists?

(2) How to print out each individual room and its information?

Additional information:

I can add rooms in the following ways:

Room r = new Room(roomNumber,roomType,price,capacity,facilities);
rooms.add(r);

(I created a 'room' class using methods such as constructor and getroomnumber()

I found that I can search the "room" list and display information that I know which room exists, such as room No. 101:

// Info for room '101'

Room room = rooms.stream()
            .filter(r -> r.getRoomNumber() == 101)
            .findFirst().orElseThrow();

System.out.println("Room Number: " + room.getRoomNumber());
System.out.println("Type: " + room.getRoomType());
System.out.println("Cost: " + room.getPrice());
System.out.println("Capacity: " + room.getCapacity());
System.out.println("Facilities: " + room.getFacilities());

The above code works normally

I try to use the try and catch above to see if a room exists (if it doesn't throw a nosuchelementfound exception), but it doesn't seem to work at all. The code doesn't even compile

I have also tried to use (with and without valueof):

Arrays.asList(rooms).contains(Integer.valueOf(401))

But it didn't really work The code compiles, but it doesn't actually do anything

So my question (as mentioned earlier) is:

(1) How do I search this list, for example, to check if a room number '401' exists?

(2) How to print out each individual room and its information?

thank you!

Solution

If you want to check a specific room and throw an exception (if it does not exist), you need to provide the exception provider to the oresethrow() method, for example:

List<Room> rooms = new ArrayList<>();
Room room = rooms.stream()
        .filter(r -> r.getRoomNumber() == 101)
        .findFirst()
        .orElseThrow(() -> new NoSuchElementException());
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>