java - 将对象添加到集合并按对象属性排序的有效方法。

标签 java hibernate

我正在尝试构建一个选择菜单对象。我正在使用 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/

相关文章:

java - 访问限制 : Is not accessible due to restriction on required library . .\jre\lib\rt.jar

java - 让 JPA 生成具有指定行格式的表

java - JDBC Hibernate - Mysql 连接错误

java - Hibernate继承单表

java - hibernate p6spy问题

java - 使用 Hibernate 和 JPA 映射 Map<String, Double>

java - JTree 首次加载时不显示句柄

java - RestAdapter Retrofit(2.0.2) 无法解析符号 android studio

Java 正则表达式匹配不正确

java - 我不明白这个 Java 示例中的代码行 "temp.next = this;"