Home > OS >  Using indexOf() method for ArrayList of objects
Using indexOf() method for ArrayList of objects

Time:09-26

In my program, I have a Vendor class and a Hospital class and store instances of these classes in arraylists called vendors and hospitals. My Vendor class has a string array with names of hospitals that correspond to instances of the Hospital class. I'm trying to find a way to go from the name of the hospital in the string array that is part of the Vendor class, to getting the index value of that hospital for the hospitals arraylist. Apologies if this post doesn't make much sense, I'm very new to coding. Any help would be greatly appreciated.

Edit: Please Ctrl F with the following to jump to the particular lines of code in question

//check if hospital

Vendor Class

package com.company;
import java.util.Arrays;
import java.util.Scanner;

public class Vendor {

    //static variables are the same for all vendor instances
    static int numOfHospitals;
    static int numOfAppointments;

    //non-static variables are specific to one vendor instance
    int priorityNum;
    String salespersonName;
    String vendorCompanyName;
    String [] vendorPicks;
    String[] vendorSchedule;

    public void printVendorSchedule() {
        System.out.println(Arrays.toString(vendorSchedule));
    }

    public void printVendorPicks () {
        System.out.println(Arrays.toString(vendorPicks));
    }

    public String getVendorSchedule (int appointmentSlot) {
        return vendorSchedule [appointmentSlot];
    }

    public String getVendorPick (int currentHospitalPick) {
        return vendorPicks[currentHospitalPick];
    }

    public boolean checkVendorSchedule (int appointmentSlot) {
        return ((vendorSchedule[appointmentSlot]).equals("open"));
    }

    public void setVendorAppointment (int appointmentSlot, String hospitalName) {
        vendorSchedule[appointmentSlot] = hospitalName;
    }

    public Vendor createNewVendor(int priorityNum, int numOfAppointments, int numOfHospitals, String salespersonName, String vendorCompanyName){
        this.priorityNum=priorityNum;
        this.salespersonName=salespersonName;
        this.vendorCompanyName=vendorCompanyName;
        this.vendorPicks = new String[numOfHospitals];
        this.vendorSchedule = new String[numOfAppointments];
        for (int i = 0; i <numOfAppointments; i  ) {
            this.vendorSchedule[i] = "open";
        }
        Scanner input = new Scanner(System.in);
        Vendor vendorToAdd = new Vendor();

        //loop to add vendor's hospital picks
        int counter = 0;
        while (counter < numOfHospitals) {
            System.out.println("Enter the #"  (counter 1)  " hospital for " salespersonName ". If there are no more hospitals for this vendor, enter Done.");
            String placeHolder = input.nextLine();
            if (placeHolder.equalsIgnoreCase("done")) {
                break;
            }
            vendorPicks[counter]=placeHolder;
            counter  ;


        }
        return vendorToAdd;
    }
}

Hospital Class

package com.company;
import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;

public class Hospital {

    //static variables here
    int numOfAppointments;
    int numOfHospitals;
    //non-static variables here
   String nameHospital;
   String nameDirector;
   String [] hospitalSchedule;

   public void printHospitalSchedule () {
       System.out.println(Arrays.toString(hospitalSchedule));
   }

   public String getHospitalSchedule(int appointmentSlot) {
       return hospitalSchedule[appointmentSlot];
   }

    public boolean checkHospitalSchedule (int appointmentSlot) {
        return ((hospitalSchedule[appointmentSlot]).equals("open"));
    }

    public void setHospitalAppointment (int appointmentSlot, String nameVendor) {
       hospitalSchedule[appointmentSlot] = nameVendor;
    }


    public Hospital createNewHospital(int numOfAppointments, int numOfHospitals,
                                       String nameHospital, String nameDirector) {
        Hospital h1 = new Hospital();
        this.nameDirector=nameDirector;
        this.nameHospital=nameHospital;
        this.hospitalSchedule = new String[numOfAppointments];
        for (int i=0; i < numOfAppointments; i  ) {
            hospitalSchedule[i] = "open";
        }
        return h1;
    }
}

Main Class

package com.company;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
import java.util.Scanner;

public class Main {



    public static void main(String[] args) {

        // Inputting #vendors, #hospitals
        int vendorCounter=1;
        System.out.println("Enter the total number of appointment slots.");
        Scanner myScanner = new Scanner(System.in);
        int numOfAppointments = Integer.parseInt(myScanner.nextLine());
        System.out.println("Enter the total number of hospitals in the draft.");
        int numOfHospitals = Integer.parseInt(myScanner.nextLine());
        ArrayList<Hospital> hospitals = new ArrayList<Hospital>();

        //creating hospitals
        int hospitalCounter = 1;
        while (hospitalCounter <=numOfHospitals) {
            System.out.println("Enter the name of hospital #"   hospitalCounter);
            String currentHospitalName = myScanner.nextLine().toLowerCase(Locale.ROOT).trim();
            System.out.println("Enter the director's name for "   currentHospitalName   ".");
            String currentDirectorName = myScanner.nextLine().toLowerCase(Locale.ROOT).trim();
            Hospital h1 = new Hospital();
            h1.createNewHospital(numOfAppointments, numOfHospitals, currentHospitalName, currentDirectorName);
            hospitals.add(h1);
            hospitalCounter  ;
        }

        //creating vendors
        ArrayList<Vendor> vendors = new ArrayList<Vendor>();
        Scanner myInput = new Scanner(System.in);
        while (vendorCounter != 2000){
            System.out.println("Are you entering a new vendor? Enter Yes or No");
            String isAddingNewVendor;
            isAddingNewVendor= myScanner.nextLine();
            if (isAddingNewVendor.equalsIgnoreCase("yes"))
            {
                System.out.println("Enter the name of the salesperson.");
                String salespersonName = myInput.nextLine();
                System.out.println("Enter the company name for " salespersonName ".");
                String vendorCompanyName = myInput.nextLine();
                Vendor v1 = new Vendor();
                v1.createNewVendor(vendorCounter, numOfAppointments, numOfHospitals,salespersonName,vendorCompanyName);
                vendors.add(v1);
                vendorCounter  ;
            }
            else vendorCounter = 2000;



        }
       /* System.out.println(vendors.get(0).vendorCompanyName);
       System.out.println(hospitals.get(0).nameHospital);
       System.out.println(vendors.get(0));
       vendors.get(0).printVendorSchedule();
       vendors.get(0).printVendorPicks();
       hospitals.get(0).printHospitalSchedule();
      if (vendors.get(0).checkVendorSchedule(0)) {
          System.out.println ("This appointment slot is open for the vendor.");
        }
      if (hospitals.get(0).checkHospitalSchedule(0)) {
          System.out.println("This appointment slot is open for the hospital.");
      }*/

        for (int i = 0; i < numOfHospitals; i  ) {
            System.out.println("Information for hospital #"   i);
            System.out.println("Hospital name: "  hospitals.get(i).nameHospital);
            System.out.println("Director's name: "   hospitals.get(i).nameDirector);
            System.out.println("The hospital's initial schedule:");
            hospitals.get(i).printHospitalSchedule();
        }

        for (int i = 0; i < vendors.size(); i  ) {
            System.out.println("Information for vendor #"   i);
            System.out.println("Salesperson's name: " vendors.get(i).salespersonName);
            System.out.println("Company name: "   vendors.get(i).vendorCompanyName);
            System.out.println("The vendor's hospital choices:");
            vendors.get(i).printVendorPicks();
            System.out.println("The vendor's initial schedule:");
            vendors.get(i).printVendorSchedule();
        }


        //draft loop logic
        int draftRound = 1;
        while (draftRound <= numOfAppointments) {
            if (draftRound % 2 == 1) {
                //insert code for odd-numbered draft rounds here.
                //these rounds should start with picker 1, then 2, 3, etc.

                int currentVendor = 0;        //starts this round with the first vendor
                while (currentVendor < vendors.size()){
                    //this while loop continues running through a single draft round until all vendors get a pick
                    int currentAppointmentSlot = 0;
                    int currentVendorPickSlot=0;
                    while (currentVendorPickSlot < numOfHospitals) {      //this loops through a single vendor until all appointments checked or appt assigned
                        //check if hospital and vendor are both open
                        String currentHospital = vendors.get(currentVendor).vendorPicks[currentVendorPickSlot];
                        System.out.println(currentHospital);
                        int currentHospitalsIndex = hospitals.indexOf(currentHospital);  //indexof is returning -1 creating the exceptionoutofbounds
                        System.out.println("Current hospital index:"  currentHospitalsIndex);
                        if ( hospitals.get(currentHospitalsIndex).checkHospitalSchedule(currentAppointmentSlot) != vendors.get(currentVendor).checkVendorSchedule(currentAppointmentSlot)) {
                            currentAppointmentSlot  ;

                        }
                        else {
                            vendors.get(currentVendor).setVendorAppointment(currentVendorPickSlot, hospitals.get(currentHospitalsIndex).nameHospital);
                            hospitals.get(currentHospitalsIndex).setHospitalAppointment(currentVendorPickSlot, vendors.get(currentVendor).salespersonName);
                            break;   // does this break the loop?
                        }
                    }

                    currentVendor  ;
                }

                draftRound  ;


            }
            if (draftRound % 2 == 0) {
                //insert code for even-numbered draft rounds here.
                //these rounds should start with the last picker and go down by 1 each turn until 1st picker.
                int currentVendor = vendors.size()-1;       //starts this draft round with the last vendor
                while (currentVendor >= 0) {
                    //this while loop continues running through a single draft round until all vendors get a pick
                    int currentAppointmentSlot = 0;                   //looping through the hospital choices for a single vendor
                    int currentVendorPickSlot=0;
                    while (currentVendorPickSlot < numOfHospitals) {
                        //check if hospital and vendor are both open
                        String currentHospital =  vendors.get(currentVendor).vendorPicks[currentVendorPickSlot];
                        int currentHospitalsIndex = hospitals.indexOf(currentHospital);
                        if (hospitals.get(currentHospitalsIndex).checkHospitalSchedule(currentAppointmentSlot) != vendors.get(currentVendor).checkVendorSchedule(currentAppointmentSlot)) {
                            currentAppointmentSlot  ;
                            //continuing the loop if the appointment slot doesn't work
                        }
                        else {
                            vendors.get(currentVendor).setVendorAppointment(currentAppointmentSlot, hospitals.get(currentHospitalsIndex).nameHospital);
                            hospitals.get(currentHospitalsIndex).setHospitalAppointment(currentAppointmentSlot, vendors.get(currentVendor).salespersonName);
                            currentVendor  ;
                            break;   // does this break the loop?
                        }
                    }

                    currentVendor  ;
                }

            draftRound  ;
            }
            else break;

        }

        for (int i = 0; i < numOfHospitals; i  ) {
            System.out.println("Information for hospital #"   i);
            System.out.println("Hospital name: "  hospitals.get(i).nameHospital);
            System.out.println("Director's name: "   hospitals.get(i).nameDirector);
            System.out.println("The hospital's final schedule:");
            hospitals.get(i).printHospitalSchedule();
        }

        for (int i = 0; i < vendors.size(); i  ) {
            System.out.println("Information for vendor #"   i);
            System.out.println("Salesperson's name: " vendors.get(i).salespersonName);
            System.out.println("Company name: "   vendors.get(i).vendorCompanyName);
            System.out.println("The vendor's final schedule:");
            vendors.get(i).printVendorSchedule();
        }

    }}

CodePudding user response:

First using stream we will Iterate through hospitals list,

find out the hospital from the list whose name equals currentHospital name, take out the first result using findFirst.

Since the result may be or may not be available it returns Optional. So on Optional, we will say if it's (the hospital object which we were looking for) present we will get the hospital out of it using the get method

Optional<Hospital> result = hospitals.stream().filter(h -> h.nameHospital.equals(currentHospital)).findFirst();

if(result.isPresent()){
    Hospital hospital = result.get();
}
  • Related