HashMap with multiple values under the same key

前端 未结 22 1753
旧时难觅i
旧时难觅i 2020-11-22 06:49

Is it possible for us to implement a HashMap with one key and two values. Just as HashMap?

Please do help me, also by telling (if there is no way) any other way to

相关标签:
22条回答
  • 2020-11-22 07:15

    Try LinkedHashMap, sample:

    Map<String,String> map = new LinkedHashMap<String,String>();    
    map.put('1','linked');map.put('1','hash');    
    map.put('2','map');map.put('3','java');.. 
    

    output:

    keys: 1,1,2,3

    values: linked,hash, map, java

    0 讨论(0)
  • 2020-11-22 07:16

    Using Java Collectors

    // Group employees by department
    Map<Department, List<Employee>> byDept = employees.stream()
                        .collect(Collectors.groupingBy(Employee::getDepartment));
    

    where Department is your key

    0 讨论(0)
  • 2020-11-22 07:17
    String key= "services_servicename"
    
    ArrayList<String> data;
    
    for(int i = 0; i lessthen data.size(); i++) {
        HashMap<String, String> servicesNameHashmap = new HashMap<String, String>();
        servicesNameHashmap.put(key,data.get(i).getServiceName());
        mServiceNameArray.add(i,servicesNameHashmap);
    }
    

    I have got the Best Results.

    You just have to create new HashMap like

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

    in your for loop. It will have same effect like same key and multiple values.

    0 讨论(0)
  • 2020-11-22 07:20

    Yes and no. The solution is to build a Wrapper clas for your values that contains the 2 (3, or more) values that correspond to your key.

    0 讨论(0)
提交回复
热议问题