我有一个LinkedList<JSONObject>
我想搜索并找到某些元素并将它们带到列表的前面。
我的实施是一个服务器响应,包含大量业务,我需要将某些业务放在列表顶部的特定字段中。有人回答了这个问题here
但这只适用于移动一个元素,因为迭代器不会指向右边的元素,它会中断。
对于多个元素,执行与此类似的操作的正确方法是什么。我很难想出一个解决方案,非常感谢帮助。谢谢。
Iterator it = list.iterator();
while (it.hasNext()) {
Object thing = it.next();
if (ThisIsTheObjectWeAreLookingFor(thing)) {
it.remove();
list.addFirst(thing);
return thing;
}
}
答案 0 :(得分: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]
答案 1 :(得分:0)
您基本上对列表中的元素进行排序要执行此操作,您可以在JSON对象中实现Comparable接口并实现compareTo()方法。
但是,如果您的JSON对象已经实现了compareTo并且您想要一个单独的算法“将项目带到前面”,请尝试使用Comparator实现并使用该比较器调用Collections.sort()
答案 2 :(得分:0)
由于列表仅包含引用而不是实际对象,因此将元素添加到新列表然后将原始列表追加到末尾可能是有意义的。
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.