如何根据每个数据项的位置构建ArrayList

时间:2015-08-17 19:30:09

标签: java sorting arraylist

假设有一组类型为[{position: 3, object3}, {position: 5, object5}, {position: 2, object2}]

的数据

如何构建一个ArrayList,其数据按位置确定,但ArrayList中没有间隙?

例如,如果数据如下所示:

arrayList[0] == object2;
arrayList[1] == object3;
arrayList[2] == object5;

我想要一个像这样的ArrayList:

class EmployeeDeleteView(DeleteView):
    success_url = reverse_lazy('index')

    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        can_delete = self.object.can_delete()

        if can_delete:
            return super(EmployeeDeleteView, self).delete(
                request, *args, **kwargs)
        else:
            raise Http404("Object you are looking for doesn't exist")

5 个答案:

答案 0 :(得分:3)

按位置对集合进行排序,然后迭代它并将每个项目添加到ArrayList。

答案 1 :(得分:1)

好问题。假设Comparable是可实现的,您可以使用compareTo方法(就像在字符串中一样)。

因此,例如,您的自定义比较器可能如下所示:

public class CustomComparator implements Comparator<MyObject> {
    @Override
    public int compare(MyObject o1, MyObject o2) {
        if (o1.position < o2.position)
            return -1;
        return 0;
    }
}

要对ArrayList进行排序,您需要致电:

Collections.sort(arrayList, new CustomComparator());

答案 2 :(得分:1)

您通过TreeSetComparator

来拨打电话
import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

class KeyPair<T> {

    private final int position;
    private final T value;

    public KeyPair(int position, T value) {
        this.position = position;
        this.value = value;
    }

    public int getPosition() {
        return position;
    }

    public T getValue() {
        return value;
    }

    @Override
    public String toString() {
        return position + " => " + value;
    }
}

public class Main {

    public static void main(String[] args) {
        TreeSet<KeyPair> set = new TreeSet<>((o1, o2) -> o1.getPosition() - o2.getPosition());

        set.add(new KeyPair<>(5, "x"));
        set.add(new KeyPair<>(1, "y"));
        set.add(new KeyPair<>(2, "z"));
        set.add(new KeyPair<>(7, "a"));
        set.add(new KeyPair<>(6, "b"));
        set.add(new KeyPair<>(0, "c"));

        set.stream().forEach(System.out::println);
    }

}

输出:

0 => c
1 => y
2 => z
5 => x
6 => b
7 => a

如果您需要ArrayList代替TreeSet,则可以执行此操作:

List<KeyPair> list = new ArrayList<>();
list.addAll(set);

这种方法的好处在于,在任何时候,如果与最后只进行排序的方法进行比较,您可以按position排序集合。

答案 3 :(得分:1)

除了sort和/或TreeSet可能是最佳选择之外,您还可以创建一个按顺序插入的方法:

public static void add( List<YourClass> list, YourClass o ) {
    for ( int i = 0 ; i < list.size(); i++ ) {
        if ( list.get(i).position() > o.position() ) {
            list.add(i, o);
            return;
        }
    }
    list.add(o);
}

完整的演示程序:

import java.util.List;
import java.util.ArrayList;
class YourClass {
    private int position;
    private String data;
    public YourClass( int position, String data ) {
        this.position = position;
        this.data = data;
    }
    public int position() {
        return position;
    }
    public String toString() {
        return String.format("{position: %d %s}", position, data);
    }
}
class Main {
    public static void main( String ... args ) {
        List<YourClass> list = new ArrayList<>();

        add( list, new YourClass(3, "object 3"));
        add( list, new YourClass(5, "object 5"));
        add( list, new YourClass(2, "object 2"));
        add( list, new YourClass(1, "object 1"));
        System.out.println(list);
    }
    public static void add( List<YourClass> list, YourClass o ) {
        for ( int i = 0 ; i < list.size(); i++ ) {
            if ( list.get(i).position() > o.position() ) {
                list.add(i, o);
                return;
            }
        }
        list.add(o);
    }
}

输出:

java Main
[{position: 1 object 1}, {position: 2 object 2}, {position: 3 object 3}, {position: 5 object 5}]

答案 4 :(得分:0)

如果您的数据确实是 位置: ,那么我首先以{i,object}的形式重新填充新的HashMap。

然后,您可以将您的hashmap条目放在TreeMap中,这将自动对它们进行排序。在您迭代TreeMap并将现在已排序的对象放入数组之后。

示例:

Map<Integer, Object> map = new TreeMap<>(yourMap);

Object[] sortedArray = new Object[map.size()];
int i = 0;
for(Map.Entry<Integer,Object> entry : map.entrySet()) {
  Object value = entry.getValue();
  sortedArray[i]=value;
  i++;
}