FixedOrderComparator BeanComparator 實現指定排序

實現根據指定的數組排序,切未指定的屬性,在指定以前

String[] strs = { "北部網信","其餘","合計","南部" };
        Arrays.sort(strs);
        log.info("-{}", JSONObject.toJSONString(strs));
        String[] sorts = { "其餘","合計" };
        FixedOrderComparator<String> fixedOrderComparator = new FixedOrderComparator<String>(sorts);
        fixedOrderComparator.setUnknownObjectBehavior(FixedOrderComparator.UnknownObjectBehavior.BEFORE);
        Arrays.sort(strs, fixedOrderComparator);
        log.info("-{}", JSONObject.toJSONString(strs));
執行結果
2019-04-12 14:25:35 [main] INFO  FixedOrderComparatorTest:29 - -["其餘","北部網信","南部","合計"]
2019-04-12 14:25:35 [main] INFO  FixedOrderComparatorTest:34 - -["北部網信","南部","其餘","合計"]

實現java bean 中屬性排序

String[] sorts = { "其餘","合計" };

        List<Team> teams = new ArrayList<>();
        Team team = new Team();
        team.setName("北部網信");
        teams.add(team);
        Team team1 = new Team();
        team1.setName("其餘");
        teams.add(team1);
        Team team2 = new Team();
        team2.setName("合計");
        teams.add(team2);
        Team team3 = new Team();
        team3.setName("南部");
        teams.add(team3);
        FixedOrderComparator<String> fixedOrderComparator = new FixedOrderComparator<String>(sorts);
        		fixedOrderComparator.setUnknownObjectBehavior(FixedOrderComparator.UnknownObjectBehavior.BEFORE);
        BeanComparator beanComparator = new BeanComparator("name",fixedOrderComparator);
        Collections.sort(teams, beanComparator);
        log.info("-{}", JSONObject.toJSONString(teams));
執行結果:
[{"name":"北部網信"},{"name":"南部"},{"name":"其餘"},{"name":"合計"}]
相關文章
相關標籤/搜索