簡體   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