繁体   English   中英

如何从对象列表中提取K个“最小”元素?

[英]How do I extract the K “smallest” elements from a list of objects?

我循环遍历List以查找特定条目,然后将其分配给变量并稍后尝试将其删除。 演示比解释更容易。

ArrayList<Example> list1 = populate();

Example ex1 = list1.get(0);
Example ex2 = ex1;
list1.remove(ex2);

我知道这可能与Java无法处理指针有关,但一个可行的解决方案会很棒。

编辑:详细说明,这是我的代码的一个简短示例,而不是给你完整的东西。 我正在做的是遍历列表以找到最低的10个数字。 我的技术是浏览列表,找到最低值并将其添加到另一个列表,然后从原始列表中删除该号码并重复。 但是我的列表是由在其中包含int值的对象组成的,而不是整数列表。

for(0 to 9){
    for(0 to list.size){
        if(list.get(x) < smallest)
            smallest = list.get(x)
    }
    smallestList.add(smallest);
    list.remove(smallest)
}

我会对清单进行排序。 然后,我将创建一个包含这10个最小对象的列表,并更改原始列表list1以包含其余对象。 就像是:

Collection.sort(list1);
ArrayList<Example> yourSmallestElements = (ArrayList<Example>)(list1.sublist(0, 9).clone());
list1.removeAll(yourSmallestElements);

注意:我克隆了子列表,因为sublist()只返回列表list1视图 ,而这不是你想要的。

您的类Example可以实现“Comparable”,以便您可以定义它们的比较方式。 您需要实现compareTo()方法。 像这样的东西:

public class Example implements Comparable<Example> {
    private int integerVal = <a value>;

    public int compareTo(Example exampleObject) {
        return exampleObject.integerVal - this.integerVal;
    }   
}

看看这个链接 ,更确切地说是从以下开始的类:

public class Fruit implements Comparable<Fruit>{

如果你想对对象进行排序......

Example e;
int min=-1; // assuming the list has +ve numbers only
for (Example elem : yourList)
{
if ( elem.gtVaribale() <= min ) //assuming you have variable field in your object
{
  e = elem;
  min = elem.getVariable();
}
}
yourList.remove(e);

//repeat this for remaining elements of the list

//you can create another sorted list, and do sortedList.add(e), so that sortedList
//have objects in ascending order (of the variable you want to sort) of objects you had in yourList

这只是一个伪代码,我没有编译它。

在这里,您必须覆盖类Example的可比方法。 你必须让编译器知道它应该将你的e变量与其列表元素进行比较的方式,以便将其删除。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM