java - 根据索引值对列表进行排序

标签 java sorting hashset linkedhashset

这是我目前所拥有的,我正在尝试对一堆 List<String> 进行排序的基于索引的值。

LinkedHashSet<List<String>> sorted = new LinkedHashSet<List<String>>();

我如何按照列表的从索引 2 的最高值到最低值对 LinkedHashSet 进行排序?

示例输入:

List<String> data1 = Database.getData(uuid);
double price = Double.valueOf(data1.get(2))

data1.add("testval");
data1.add("testval");
data1.add("100.00");

sorted.add(data1);

在另一个单独的列表中:

List<String> data2 = Database.getData(uuid);
double price = Double.valueOf(data2.get(2))

data2.add("anotherval");
data2.add("anotherval");
data2.add("50.00");

sorted.add(data2);

排序的 LinkedHashSet 的输出按降序排列。

testval testval 100.00
anotherval anotherval 50.00

抱歉,如果这令人困惑,我不确定去哪里进行这样的排序。

最佳答案

创建一个新类来表示您的复杂对象。如果可以在对象中存储多个值,则无需在列表中存储多个值。

public class ComplexObject {
    private String description1;
    private String description2;
    private Double value;

    public ComplexObject(String description1, String description2, Double value) {
        this.description1 = description1;
        this.description2 = description2;
        this.value = value;
    }

    public void setDescription1(String description1) {
        this.description1 = description1;
    }

    public String getDescription1() {
        return description1;
    }

    public void setDescription2(String description2) {
        this.description2 = description2;
    }

    public String getDescription2() {
        return description2;
    }

    public void setValue(Double value) {
        this.value = value;
    }

    public Double getValue() {
        return value;
    }
}

然后将元素添加到列表中并使用新的自定义比较器对其进行排序:

public static void main(String[] args) {

    List<ComplexObject> complexObjectList = new ArrayList<ComplexObject>();

    //add elements to the list
    complexObjectList.add(new ComplexObject("testval","testval",100.00d));
    complexObjectList.add(new ComplexObject("anotherval","anotherval",50.00d));

    //sort the list in descending order based on the value attribute of complexObject
    Collections.sort(complexObjectList, new Comparator<ComplexObject>() {
            public int compare(ComplexObject obj1, ComplexObject obj2) {
                return obj2.getValue().compareTo(obj1.getValue()); //compares 2 Double values, -1 if less , 0 if equal, 1 if greater
            }
        });

    //print objects from sorted list
    for(ComplexObject co : complexObjectList){
        System.out.println(co.getDescription1()+" "+co.getDescription2()+" "+co.getValue());
    }
}

输出:

testval testval 100.0
anotherval anotherval 50.0

关于java - 根据索引值对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27359074/

相关文章:

java - 链表排序

javascript - 在 Javascript 中连续打印 X 数量的项目

delphi - Delphi中有HashSet吗?

java - Android 首选项屏幕,仅全屏?

java - 去除所有长度小于或大于 6 的数字

java - 使用 lambda 时如何修复 "unexpected return value"?

ruby-on-rails - 按字段可用性对对象排序

java - 为什么我的 HashSet 存储 2 个具有相同 hashCode 的相同对象?

rust - 如何实现一个HashSet对,以防止插入重叠值?

java - HTTPClient 和 PostMethod