开发者

Sorting Vector according to given sequence

For a given vector like this,

Vector<Temp> s = new Vector<Temp>();
s.add(new Temp("a",1));
s.add(new Temp("b",2));
s.add(new Temp("c",3));
s.add(new Temp("b",4));
s.add(new Temp("b",6));
s.add(new Temp("c",5));

desired sequencing(b,a,c)

after sorting, it 开发者_Go百科should be like

b,2  
b,4  
b,6  
a,1  
c,3  
c,5 

I know how to use comparator to sort objects according to one field, but here the problem is different, the desired sequence varies, and I have to sort according to that sequence every time.

Any ideas?


You should write a custom comparator that takes the sequence as argument, and compares the elements accordingly.

Here is an example implementation:

public class Test {
    public static void main(String[] args) {
        Vector<Temp> s = new Vector<Temp>();
        s.add(new Temp("a",1));
        s.add(new Temp("b",2));
        s.add(new Temp("c",3));
        s.add(new Temp("b",4));
        s.add(new Temp("b",6));
        s.add(new Temp("c",5));

        String[] seq = { "b", "a", "c" };

        Collections.sort(s, new CustomComparator(seq));

        for (Temp tmp : s)
            System.out.println(tmp);
    }

    static class CustomComparator implements Comparator<Temp> {
        List<String> sequence;

        CustomComparator(String[] seq) {
            sequence = Arrays.asList(seq);
        }

        public int compare(Temp t1, Temp t2) {
            if (t1.s.equals(t2.s))
                return ((Integer) t1.i).compareTo(t2.i);
            return sequence.indexOf(t1.s) - sequence.indexOf(t2.s);
        }
    }
}

Output: (ideone.com demo)

(b, 2)
(b, 4)
(b, 6)
(a, 1)
(c, 3)
(c, 5)


Just a quick idea: you may build a map {b->0, a->1, c->2} representing your sequence and then use mapped values in the comparator instead of actual fields.


You can still use a comparator. First compare the String fields and if equal rather than returning 0 compare the int fields. Your Comparator would only return zero if both fields are identical.


A comparator is still applicable here. Implement the comparable interface in your class and use both the sequence and the value as part of your compareTo() logic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜