2016-10-30 3 views
0

현재 HashMap을 반환하려고합니다. 매개 변수가 ArrayList이고 항목이 50 개 이상입니다. 내가 값으로 키와 의사 객체로 아이디를 전달하고개체 목록에서 HashMap을 반환하는 방법?

public static HashMap<String, Doctor> getDoctorHash(ArrayList<Doctor> doctorList) { 

    HashMap<String, Doctor> hm = new HashMap<>(); 

    for(Doctor doctor : doctorList) { 
     hm.put(doctor.getId(), doctor); 
    } 

    return hm; 
} 

..

Doctor 클래스는 간단하다 :

public class Doctor { 
    private String firstName, lastName, id; 

    public Doctor(String firstName, String lastName, String id) { 
     this.firstName = firstName; 
     this.lastName = lastName; 
     this.id = id; 
    } 
    //getter and setters etc. 
} 
+0

변경에는 EmployeeList을 and Doctor.size() to doctorList.size() – developer

+1

['HashMap'] (https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html)은 매핑을 정의하고, 예 당신의 예제에서 당신은'String'으로 질의를하고'Doctor'를 얻을 것입니다. 따라서 [put (K key, V value)'] (https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#put-KV-)에는 두 개의 매개 변수가 필요합니다 . 어쩌면 ['HashSet'] (https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html)을 사용하고 싶습니까? – Turing85

+4

열쇠는 무엇이되어야합니까? Map의 포인트는 값을'Key'와 연결하는 것입니다.이 경우'String'으로 지정했습니다. 그래서 특정'Doctor' (일명'put ("Bob",/* some doctor * /))와 연관되는'String' 값이 필요합니다.'get ("Bob")' – Rogue

답변

1

하지 당신이이 방법을 수행 할 확실한 이유 , (당신은 Java8 스트림을 사용할 수 있고, filter 이름의 목록), 당신은 가깝습니다.

public static HashMap<String, Doctor> getDoctorHash(ArrayList<Doctor> doctorList) { 

    HashMap<String, Doctor> hm = new HashMap<>(); 

    for(int i = 0; i < doctorList.size(); i++) { 
     hm.put(doctorList.get(i).getFirstName(), doctorList.get(i)); 
    } 

    return hm; 
} 

또는, 더 간단하게

public static HashMap<String, Doctor> getDoctorHash(ArrayList<Doctor> doctorList) { 

    HashMap<String, Doctor> hm = new HashMap<>(); 

    for(Doctor d : doctorList) { 
     hm.put(d.getFirstName(), d); 
    } 

    return hm; 
} 

그런 다음 몇 가지 firstname

+0

문제가 지속되는 것으로 나타났습니다. 생성 된 HashMap의 키 중 하나의 값을 얻으려고하면 콘솔은 NullPointerException 오류를 반환합니다. 그럼에도 불구하고 그 이유는 무엇인지에 대해 조금이라도 생각하지 못했습니다. – SpaceCore186

+0

무슨 뜻인지 모르겠다. 목록에 null이 아닌 Doctor 객체가 있으면 NPE를 throw하지 않습니다. –

+0

내 대답에 구현 된 첫 번째 스 니펫은 getDoctorHash() 함수의 정의 안에 Doctor 객체가 처음에는 null이 아닌지 확인하는 데 사용되는 System.out.println() 문이 있습니다. . 이것에도 불구하고, 나중에 NPE가 던져진다. – SpaceCore186

0

에 대한 Doctor d = doctorMap.get("firstname")에있는이 솔루션은 아니지만,에서 하나를 도출 사용할 수 있습니다 뭔가

콘솔의 출력 내용을 밝히지 않았기 때문에 kn을 할 수 없습니다. 특정 오류가있는 이유. 항목의 값을 되 Doctor 대상으로 그런 일이없는 것처럼 컴파일러는 역할을한다는

public class StartingPoint { 

    static String[] doctorNames = {"Potato", "Chocolate", "Something", "Name", "Unnamed"}; 

    public static void main(String[] args) {    

     ArrayList<Doctor> doctorList = new ArrayList<>(5); 

     for (int i = 0; i < 5; i++) { 
      doctorList.add(new Doctor(doctorNames[i], doctorNames[i] + " last name", String.valueOf(i))); 
     } 

     HashMap<String, Doctor> someHashMap = getDoctorHash(doctorList); 

     for (int i = 0; i < 5; i++) { 
      System.out.println("The ID of the doctor number " + String.valueOf(i + 1) + " is: "); 
      System.out.println(someHashMap.get(doctorNames[i]).getId()); 
     } 
    } 

    public static HashMap<String, Doctor> getDoctorHash(ArrayList<Doctor> doctorList) { 

     HashMap<String, Doctor> hm = new HashMap<>(); 

     for(Doctor doctor : doctorList) { 
      System.out.println(doctor); 
      hm.put(doctor.getId(), doctor); 
     } 

     return hm; 
    } 

} 

그것은 밝혀 :

그럼에도 불구하고, 나는 나 자신에게 아이디어를 제공하기위한 다음 코드를 생성 ID (키 역할을 함). 그럼에도 불구하고, 함수에 전달 된 ArrayList의 항목 중 Doctor 항목 각각의 메모리에있는 위치를 인쇄하려고하면 아무런 문제가 없음을 알 수 있습니다. 나는 이것의 이유가 무엇인지에 대해 조금이라도 생각하지 못했습니다.

하지만, 대신 우리는 그 방법 중 하나를 이용하여 얻을 수있는 String들 중 하나를 사용하는 값으로 Doctor 객체를 사용하는 모든 것이 잘 밝혀지면 : doctorList에

public class StartingPoint { 

    static String[] doctorNames = {"Potato", "Chocolate", "Something", "Name", "Unnamed"}; 


    public static void main(String[] args) { 

     ArrayList<Doctor> doctorList = new ArrayList<>(5); 

     for (int i = 0; i < 5; i++) { 
      doctorList.add(new Doctor(doctorNames[i], doctorNames[i] + " last name", String.valueOf(i))); 
     } 

     HashMap<String, String> someHashMap = getDoctorHash(doctorList); 

     for (int i = 0; i < 5; i++) { 
      System.out.println("The first name of the doctor number " + String.valueOf(i + 1) + " is: "); 
      System.out.println(someHashMap.get(String.valueOf(i))); 
     } 
    } 

    public static HashMap<String, String> getDoctorHash(ArrayList<Doctor> doctorList) { 

     HashMap<String, String> hm = new HashMap<>(); 

     for(Doctor doctor : doctorList) { 
      hm.put(doctor.getId(), doctor.getFirstName()); 
     } 

     return hm; 
    } 

} 
관련 문제