2014-05-01 35 views
-1

我有一個LinkedList<JSONObject>,我想要搜索並找到某些元素,並將它們放在列表的前面。Java LinkedList,將多個元素移動到頂部

我的實現是一系列業務的服務器響應,我需要將某個業務的特定字段放在列表頂部。有人回答了這個問題here

但是,這隻適用於移動一個元素,因爲迭代器不會指向正確的元素後,它會中斷。

什麼是正確的方式做一些非常相似的事情,但對於多個元素。我很難提出解決方案,並非常感謝幫助。謝謝。

Iterator it = list.iterator(); 
while (it.hasNext()) { 
    Object thing = it.next(); 
    if (ThisIsTheObjectWeAreLookingFor(thing)) { 
     it.remove(); 
     list.addFirst(thing); 
     return thing; 
    } 
} 
+0

只需編寫一個知道如何排序元素的比較器,然後進行排序。 –

+0

可能這也會拋出'ConcurrentModificationException',因爲你修改列表而不使用迭代器的方法? – awksp

回答

1

您可以使用Collections.Sort來完成此操作。這裏有一個例子:

import java.util.Arrays; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.List; 

public class MoveItemsToTop { 
    public static void main(String[] args) { 
     final List<String> items = Arrays.asList(new String[] { "one", "two", "three", "four", "five" }); 
     final List<String> thingsImLookingFor = Arrays.asList(new String[]{"two", "four"}); 

     Collections.sort(items, new Comparator<String>() { 
      @Override 
      public int compare(String o1, String o2) { 
       if (thingsImLookingFor.contains(o1)) { 
        return -1; 
       } 
       return 0; 
      } 
     }); 

     System.out.println(items); 
    } 
} 

這個節目輸出

[four, two, one, three, five] 
0

你基本上排序你在你的名單要做到這一點具備的要素,可以實現Comparable接口在你的JSON對象和實施compareTo()方法。

但是,如果你的JSON對象已經實現了的compareTo和你想要一個獨立的算法中的「引進項目前」,請嘗試使用比較實施,並與比較

0

的調用Collections.sort()由於名單隻保留引用而不保留實際對象,只需將元素添加到新列表中,然後將原始列表追加到最後即可。

LinkedList headList = new LinkedList(); 
Iterator it = list.iterator(); 
while (it.hasNext()) { 
    Object thing = it.next(); 
    if (ThisIsTheObjectWeAreLookingFor(thing)) { 
     it.remove(); 
     headList.addFirst(it); 
    } 
} 
headList.addAll(list); // add remainder of the original list to the end of the new headlist. 
list = headList; // Assign the original list reference to be the new list. 
相關問題