我正在尝试构建一个选择菜单对象。我正在使用 hibernate 标准来构建我的对象列表。我正在尝试将连接的表对象添加到集合中以消除重复项。然后,我想通过对象内的属性对集合进行排序,一旦排序,我需要将其添加到数组列表中,最后在列表末尾添加一个附加条目。
这是我迄今为止所拥有的。
public class Computer {
private String name;
//other properties getter/setter
}
选择菜单查询
public List<Computer> getComputerList() {
//Hibernate critera query
List<ComputerConfiguration> results = session.criteraQuery(ComputerConfiguration.class).add(Restrictions.eq("processor", "amd")).list();
Set<Computer> computerSet = HashSet();
//Get joined object and add to set to remove duplicates
for(ComputerConfiguration computerConfiguration : results) {
computerSet.add(computerConfiguration.getComputer());
}
List<Computer> computers = new ArrayList<>(computerSet);
//Need to somehow order by computer.getName();
//Lastly add the following
computers.add("Other");
//Return computers to select model
return computers;
}
删除重复对象然后按属性名称对它们进行排序的最有效方法是什么?我最初尝试订购标准查询,但是该集似乎没有保持其位置。
谢谢。
最佳答案
使用 TreeSet
这将对其中的元素进行排序。您可以在创建集合时提供自定义Comparator
:
Set<Computer> computerSet = new TreeSet<Computer>(new Comparator<Computer>() {
@Override
public int compare(Computer computer1, Computer computer2) {
//write the logic to define which computer is greater than the other...
}
});
请注意,您的 Computer
类不需要实现 equals
也不需要实现 hashCode
即可在 TreeSet
中使用>.
关于java - 将对象添加到集合并按对象属性排序的有效方法。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22150190/