I have an hibernate entity class:
@Entity
@Table(name = "grade")
@JsonIgnoreType
public class StudentMaster implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "grade_id", unique = true, nullable = false)
private Integer gradeId;
@Column(name = "grade_name")
private String gradeName;
//getter and setter
}
I have written a query that return a list of object array: String query = select T.gradeId, T.gradeName from grade where available = 1;
This return a list of object array
List<Object[]> list = session.createQuery(query.toString()).list();
List is coming like
[0]
>[0] = 5001
>[1] = "10"
[1]
>[0] = 5002
>[1] = "11"
[2]
>[0] = 5003
>[1] = "4"
[3]
>[0] = 5004
>[1] = "18"
and so on....
I am trying to sort this in ascending order like 4, 10, 11, 18 I tried with the below code snippet but didn't work
Collections.sort(list, new Comparator<StudentMaster>() {
public int compare(StudentMaster s1, StudentMaster s2) {
return s1.getGradeName().compareTo(s2.getGradeName());
}
});
can someone help me here. I am learning myself and new to coding so need help. Thank you
I would suggest to let DB to do its best and sort it for you. Just add order by to your query.
Update:
Since you want to order by integer value stored as string, you need to convert it to integer, using TO_NUMBER
or specific SQL dialect syntax. In-memory sorting could be implemented like this:
new Comparator<Object[]>() {
public int compare(Object[] o1, Object[] o2) {
return Integer.valueOf((String) o1[1]).compareTo(Integer.valueOf((String) o2[1]));
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.