我如何将这些java collection.sort语句合并为一个?

时间:2013-10-09 13:15:01

标签: java sorting for-loop collections

我有这个代码可以为不同的卡套件(俱乐部,钻石,心形和黑桃)分类我的数组列表。有没有办法编写以下代码,所以我不必为每个ArrayList编写它?

        String clubsLabel = "Clubs";
        String diamondsLabel = "Diamonds";
        String heartsLabel = "Hearts";
        String spadesLabel = "Spades";

        Collections.sort(clubs, new cardIdSorter());
        System.out.printf("%-12s", clubsLabel);
        for(PlayingCard clubsCard: clubs) {
            System.out.print(clubsCard);
        }

        System.out.println(" ");

        Collections.sort(diamonds, new cardIdSorter());
        System.out.printf("%-12s", diamondsLabel);
        for(PlayingCard diamondsCard: diamonds) {
            System.out.print(diamondsCard);
        }

        System.out.println(" ");

        Collections.sort(hearts, new cardIdSorter());
        System.out.printf("%-12s", heartsLabel);
        for(PlayingCard heartsCard: hearts) {
            System.out.print(heartsCard);
        }

        System.out.println(" ");

        Collections.sort(spades, new cardIdSorter());
        System.out.printf("%-12s", spadesLabel);
        for(PlayingCard spadesCard: spades) {
            System.out.print(spadesCard);
        }

4 个答案:

答案 0 :(得分:2)

编写自定义方法并调用每个集合。

public static void sortAndPrintCollection(Collection col,String var){   
Collections.sort(col, new cardIdSorter());
        System.out.printf("%-12s", var);
        for(PlayingCard p: col) {
            System.out.print(p);
        }}

使用示例

ClassName.collectionSorter(clubs,clubsLabel);

答案 1 :(得分:1)

定义这样的方法 -

public void sortAndPrint(ArrayList<PlayingCard> cards, String label) {
    Collections.sort(cards, new cardIdSorter());
    System.out.printf("%-12s", label);

    for(PlayingCard card: cards) {
        System.out.print(card);
    }
}

然后这样称呼它 -

sortAndPrint(clubs, "Clubs");
sortAndPrint(diamonds, "Diamonds");
sortAndPrint(hearts, "Hearts");
sortAndPrint(spades, "Spades");

答案 2 :(得分:1)

将您的代码分成一个方法:

void sortAndPrint(List<PlayingCard> cards, String label) {
    Collections.sort(cards, new cardIdSorter());
    System.out.printf("%-12s", label);
    for(PlayingCard card: cards) {
        System.out.print(card);
    }
}

然后为每组卡片调用该方法一次:

sortAndPrint(clubs, clubsLabel);
sortAndPrint(diamonds, diamondsLabel);
sortAndPrint(hearts, heartsLabel);
sortAndPrint(spades, spadesLabel);

答案 3 :(得分:0)

我没有测试过,但你可能会做这样的事情。

Map<> suites = new HashMap<String, ArrayList<PlayingCard>>() {{
    put("Clubs",clubs); put("Diamonds",diamonds); put("Hearts",hearts); put("Spades",spades);
}};

for (Map.Entry<String, ArrayList<PlayingCard>> entry : suites.entrySet()) {
    Collections.sort(entry.getValue(), new cardIdSorter());
    System.out.printf("%-12s", entry.getKey());
    for(PlayingCard card: entry.getValue()) {
        System.out.print(card);
    }
}

欢迎使用Java,重构代码以删除重复通常只会让它变得更加难看。请注意,这将创建一个新的内部类来进行地图初始化。