如何计算ArrayList中的多个重复元素?

时间:2016-05-05 00:02:43

标签: java for-loop arraylist count duplicates

我有一个程序,它接收乐队和专辑的文件列表。我需要确定每个乐队制作的专辑数量,然后打印出乐队列表和他们按降序排列的专辑数量。我环顾四周,看到它使用映射和集合完成。我想知道怎么做也没有。以下是我到目前为止的情况:

public static void processFile(String filename)
{
    String bandname = "";
    String[][] data = read_spreadsheet(filename);
    //takes the file and converts it to a 2d array
    ArrayList<String> bands = new ArrayList<String>();
    for(int rows = 0; rows < data.length; rows++)
    {
        bands.add(data[rows][0]);
    }

    for(int i = 0; i<bands.size()-1;i++)
    {
        int albumcount = 0;
        for(int j = i+1; j<bands.size();j++)
        {
            if(bands.get(i).equals(bands.get(j)))
            {
                albumcount++;
            }
        }
    }
}

输入示例:

band1 -album
band2 -album
band1 -album
band3 -album
band1 -album
band2 -album

输出示例:

band1: 3
band2: 2
band3: 1

2 个答案:

答案 0 :(得分:0)

没有收藏?你想使用数组吗?

String [] names = new String[data.length];
int [] counts = new int[data.length];

int j = 0;
for (int i = 0; i < data.lenght; i++ ) {
   while (j < data.length) {
      if (data[i][0].equals(names[j])) {
         found = true;
         counts[j]++;
         break;
      } else if (names[j] == null) {
         names[j] = data[i][0];
         counts[j]=1;
         break;
      }
      j++;
   }
}

// find max count
// println
// nullify element
// repeat

for (int i = 0; i < j; i++) {
    int max = -1;
    int k = i;
    int pos = -1;
    while ( k < j ) {
       if ( counts[k] > max ) {
          pos = k;
          max = counts[k];
       }
       k++;
    }
    if ( pos != -1 ) { // we found 
       System.out.println ( names[pos] + ": " + counts[pos]);
       counts[pos] = -1;
    }
}

答案 1 :(得分:0)

如果您对乐队名称列表(带有重复项)进行排序,然后计算列表中每个乐队名称的数量,您将获得每个乐队的专辑数量:

public static void processFile(String filename)
{
    //takes the file and converts it to a 2d array
    String[][] data = read_spreadsheet(filename);

    // get all the bands (with duplicates)
    ArrayList<String> bands = new ArrayList<String>();
    for(int rows = 0; rows < data.length; rows++) {
        bands.add(data[rows][0]);
    }

    // sort the bands alphabetically
    Collections.sort(bands);

    int albumCount = 1;
    String currentBand = bands.remove(0);
    while(bands.size() > 0) {
        String nextBand = bands.remove(0);
        if(currentBand.equals(nextBand)) {
            albumCount++;
        } else {
            // print the current band album count and setup for the next band
            System.out.println(currentBand + ": " + albumCount);
            currentBand = nextBand;
            albumCount = 1;
        }
    };
    // print the final band album count
    System.out.println(currentBand + ": " + albumCount);
}