Home > Back-end >  Adding the ArrayList<StudentBean> values to HashMap<Integer, StudentBean>
Adding the ArrayList<StudentBean> values to HashMap<Integer, StudentBean>

Time:11-22

I have a List:

List<StudentBean> resultList

StudentBean has something like with getters and setters:

{ Integer StudentId, String StudentName, String Section}.

I have a map with values: Map<Integer, StudentBean> orginialStudentDetails

Now I want to add/replace the values from resultList to orginialStudentDetails, how can I achieve that?

Tried:

for (Map.Entry<Integer, StudentBean> entry : resultList .size()){
     orginialStudentDetails.put(entry.getKey(), resultList );
}

CodePudding user response:

I don't know what the class StudentBean look like, but something like the following might work.

for (StudentBean studentBean : resultList) {
    originalStudentDetails.put(studentBean.getStudentId(), studentBean);
}

This is assuming that StudentBean has a method called getStudentId that returns an int or Integer.

CodePudding user response:

Java 8, by lambda:

Map<Integer, StudentBean> map = resultList.stream().filter(t -> t != null || t.getStudentId() != null).collect(Collectors.toMap(StudentBean::getStudentId, t -> t));

StudentId must not be repeat or null, or there will be a duplicate key exception.

  • Related