开发者

Sorting list based on its element's value

How to sort list based on its element value?

In my unit test class, I am receiving list which is in sorted form based on one of its element's value {sortOrder and it has value 1, 2 and 3} now I am comparing returnedList with expectedList to make sure that both list are same and have same elements in same order.

Example of my return and expected list:

expected List = [Code: ANALYST, SortOrder: 2, Code: STREET, SortOrder: 1]

and returned List = [Code: STREET, SortOrder: 1, Code: ANALYST, SortOrder: 2]

So how can i sort the list on SortOrder so that my expected list becomes:

expected L开发者_如何学Cist = [Code: STREET, SortOrder: 1, Code: ANALYST, SortOrder: 2]

I cannot use any libraries and this question is related to Compare List Question, any suggestions?


use this:

 public static void sort(List list, Comparator c)

So do something like this:

Collections.sort(myList, myComparator)

myComparator is an interface for which you only have to implement one method which is compare:

public int compare(Object o1, Object o2)

So you can do this with an anonymous inner class:

Collections.sort(myList, new Comparator<MyType>(){ 
    public int compare(MyType o1, MyType o2) { 
        //My implementation
    }
 });

For information on how to implement the compare method take a look at the documentation here:

Comparator


If you don't mind to modify the list returned, you have two options:

  • If you can modify the object (that you have a list of), implement Comparable and override the compareTo(MyObject) method.

  • If you cannot modify the object, then create a Comparator and pass it to your sort method.

If you cannot modify the list, do something like this:

List<MyObject> newList = new ArrayList<MyObject>();
newList.addAll(reterunedList);
newList.removeAll(expectedList);
// check here (newList.size() > 0 ?)
expectedList.removeAll(returnedList);
// check here (expectedList.size() > 0 ?)

If there is anything left in the lists in either of those two checks it means your lists are different. And you haven't modified your returned list. It requires your MyObject to have implemented the equals() method properly.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜