Ordering with partial explicit and then another order?

后端 未结 2 1440
Happy的楠姐
Happy的楠姐 2021-01-21 05:10

What I need is to order a list in a custom way, I\'m looking into the correct way and found guava\'s Ordering api but the thing is that the list I\'m ordering is not always goin

2条回答
  •  无人及你
    2021-01-21 06:02

    Here's a Comparator solution that uses a List of strings to represent your sorting order. Change your sorting order by merely changing the order of the strings in your sortOrder list.

      Comparator accountTypeComparator = (at1, at2) -> {
        List sortOrder = Arrays.asList(
            "rrsp",
            "tfsa",
            "third"
            );
        int i1 = sortOrder.contains(at1.type) ? sortOrder.indexOf(at1.type) : sortOrder.size();
        int i2 = sortOrder.contains(at2.type) ? sortOrder.indexOf(at2.type) : sortOrder.size();
        return i1 - i2;
      };
      accountTypes.sort(accountTypeComparator);
    

提交回复
热议问题