最后添加的地图记录的值将覆盖现有记录的值

时间:2019-05-25 09:07:32

标签: collections

我被要求编写代码以找出薪水总和,明智的是,数据以字符串数组形式给出       {              String [] details = new String [] {“ a,it,100”,“ b,sales,200”,“ c,hr,300”,“ d,it,150”,“ e,hr,120”, “ f,sales,300”};

  }
i am converting an string array of employee details to individual emp details [map object] and adding that map object to another map having key as dept of the current employee, i have successfully converted the details to individual employee map object but while adding this map obj to another map object like below  
     {    {dept,empDetailsObj},     {dept,empDetailsObj},       
      {dept,empDetailsObj}    } 


i am facing issue, my empDetailsObj is getting overridden by last record while the keys are still unique.
i have used TreeMap obj "empDetailsMap" and added each employee details in this format 

     {    name:a,dept:it,sal:100       }
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I have used another TreeMap "empRecordsMap " to add the above individual record with dept as key which is expected to be like this 
         {
         {     it=   {dept=it,name=a,salary=100}, 
             sales=   {dept=sales, name=b, salary=200}, 
                hr=   {dept=hr, name=c, salary=120}, 
                it=   {dept=it, name=e, salary=250}}


    {
  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~  
     public static void main(String[] args) {
     String[] details = new String[] {
     "a,it,100",
     "b,sales,200",
     "c,hr,300",
     "d,it,150",
     "e,hr,120",
     "f,sales,300"
     };
     List < String > empRecordList = new ArrayList();
     Map eachEmpDetailsMap = new TreeMap();
     Map eachEmpRecordMap = new TreeMap();
     for (String records: details) {
     String[] empRecord = records.split(",");
     String[] keys = {
     "name",
     "dept",
     "sal"
     };
     int i = 0;
     String dept = "";
     for (String info: empRecord) {
     eachEmpDetailsMap.put(keys[i], info);
     if (i == 1) {
     dept = info;
     }
     i++;
     }
     System.out.println("--------------------------");
     System.out.print(dept + "::  ");
     System.out.println(eachEmpDetailsMap.toString());
     System.out.println("--------------------------");
     eachEmpRecordMap.put(dept, eachEmpDetailsMap);
     System.out.println("================================");
     System.out.println(eachEmpRecordMap.toString());
     }
     }



     } 


    Expected o/p:  
         {it = {dept=it,name=a,salary=100}, 
          hr =   {dept=hr, name=c, salary=120}, 
          it =  {dept=it, name=e, salary=250},
          sales=  {dept=sales, name=b, sal=200}}
          Actual o/p:
          last added value is replacing all existing keys's value.
          {it={dept=sales, name=b, sal=200}, sales={dept=sales, name=b, 
           sal=200}}

0 个答案:

没有答案