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

标签 java sorting for-loop collections

我有这段代码可以根据不同的牌组(梅花、方 block 、红心和黑桃)对数组列表进行排序。有什么方法可以编写以下代码,这样我就不必为每个 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);
        }

最佳答案

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

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);

关于java - 我如何将这些 java collection.sort 语句合并为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19273132/

相关文章:

java - REST是API,还是: REST vs Java Interface?

java - 如何在 Seekbar 上放置箭头作为选择器

java - 创建新 Excel 文件时如何初始化单元格 (Apache POI)

java - 根据对象数据类型对列表对象进行排序

c++ - 如何打印数组元素的索引号?

Java:A类中的队列

matlab - 在Matlab中总结每第n行

java - AndEngine - 一般 2D 横向卷轴问题

perl - 有这种类型的名称吗?

ios - 如何查看 Swift 字典中存在的数组?