Java计数数组中每个项目的出现次数

时间:2011-11-11 18:54:35

标签: java arrays count

是否有任何方法可以计算数组中每个项目的出现次数?

让我说我有:

String[] array = {"name1","name2","name3","name4", "name5"};

这里的输出将是:

name1 1
name2 1
name3 1
name4 1
name5 1

如果我有:

String[] array = {"name1","name1","name2","name2", "name2"};

输出结果为:

name1 2
name2 3

此处的输出仅用于演示预期结果。

18 个答案:

答案 0 :(得分:36)

List asList = Arrays.asList(array);
Set<String> mySet = new HashSet<String>(asList);
for(String s: mySet){

 System.out.println(s + " " +Collections.frequency(asList,s));

}

答案 1 :(得分:20)

使用,您可以这样做:

String[] array = {"name1","name2","name3","name4", "name5", "name2"};
Arrays.stream(array)
      .collect(Collectors.groupingBy(s -> s))
      .forEach((k, v) -> System.out.println(k+" "+v.size()));

输出:

name5 1
name4 1
name3 1
name2 2
name1 1

它的作用是:

  • 从原始数组
  • 创建Stream<String>
  • 按身份对每个元素进行分组,生成Map<String, List<String>>
  • 对于每个键值对,打印键和列表大小

如果你想获得一个包含每个单词出现次数的Map,可以这样做:

Map<String, Long> map = Arrays.stream(array)
    .collect(Collectors.groupingBy(s -> s, Collectors.counting()));

了解更多信息:

希望它有所帮助! :)

答案 2 :(得分:17)

您可以使用Google Collections / Guava中的MultiSet或来自Apache Commons的Bag

如果您有一个集合而不是一个数组,则可以使用addAll()将整个内容添加到上述数据结构中,然后将count()方法应用于每个值。 SortedMultiSetSortedBag会按照定义的顺序为您提供商品。

Google Collections实际上有非常便捷的方式从数组转到SortedMultiset

答案 3 :(得分:3)

我会使用带键的哈希表获取数组的元素(此处为字符串),值为整数。

然后通过列表执行以下操作:

for(String s:array){
if(hash.containsKey(s)){
  Integer i = hash.get(s);
  i++;
}else{
  hash.put(s, new Interger(1));
}

答案 4 :(得分:3)

我为此自己写了一个解决方案。它似乎并不像发布的其他答案那样令人敬畏,但无论如何我都会发布它,然后使用其他方法学习如何做到这一点。享受:

public static Integer[] countItems(String[] arr)
{
    List<Integer> itemCount = new ArrayList<Integer>();
    Integer counter = 0;
    String lastItem = arr[0];

    for(int i = 0; i < arr.length; i++)
    {
        if(arr[i].equals(lastItem))
        {
            counter++;
        }
        else
        {
            itemCount.add(counter);
            counter = 1;
        }
        lastItem = arr[i];
    }
    itemCount.add(counter);

    return itemCount.toArray(new Integer[itemCount.size()]);
}

public static void main(String[] args)
{
    String[] array = {"name1","name1","name2","name2", "name2", "name3",
            "name1","name1","name2","name2", "name2", "name3"};
    Arrays.sort(array);
    Integer[] cArr = countItems(array);
    int num = 0;
    for(int i = 0; i < cArr.length; i++)
    {
        num += cArr[i]-1;
        System.out.println(array[num] + ": " + cArr[i].toString());
    }
}

答案 5 :(得分:2)

使用HashMap,它在公园散步。

main(){
    String[] array ={"a","ab","a","abc","abc","a","ab","ab","a"};
    Map<String,Integer> hm = new HashMap();

    for(String x:array){

        if(!hm.containsKey(x)){
            hm.put(x,1);
        }else{
            hm.put(x, hm.get(x)+1);
        }
    }
    System.out.println(hm);
}

答案 6 :(得分:1)

您可以使用Arrays.sort和Recursion来完成。相同的葡萄酒,但在不同的瓶子....

import java.util.Arrays;

public class ArrayTest {
public static int mainCount=0;

public static void main(String[] args) {
    String prevItem = "";
    String[] array = {"name1","name1","name2","name2", "name2"};
    Arrays.sort(array);

    for(String item:array){
        if(! prevItem.equals(item)){
            mainCount = 0;
            countArray(array, 0, item);
            prevItem = item;
        }
    }
}

private static void countArray(String[] arr, int currentPos, String item) {
    if(currentPos == arr.length){
        System.out.println(item + " " +  mainCount);
        return;
    }
    else{
        if(arr[currentPos].toString().equals(item)){
            mainCount += 1;
        }
        countArray(arr, currentPos+1, item);
    }
  }
}

答案 7 :(得分:1)

可以使用集合以非常简单的方式完成 请找到下面的代码

String[] array = {"name1","name1","name2","name2", "name2"};
List<String> sampleList=(List<String>) Arrays.asList(array);
for(String inpt:array){
int frequency=Collections.frequency(sampleList,inpt);
System.out.println(inpt+" "+frequency);
}

这里的输出就像 name1 2 name1 2 name2 3 name2 3 name2 3

要避免打印冗余密钥,请使用HashMap并获取所需的输出

答案 8 :(得分:1)

这是我的解决方案 - 该方法将一个整数数组(假设范围在0到100之间)作为输入,并返回每个元素的出现次数。

假设输入为[21,34,43,21,21,21,45,65,65,76,76,76]。 因此输出将在地图中,它是:{34=1, 21=4, 65=2, 76=3, 43=1, 45=1}

public Map<Integer, Integer> countOccurrence(int[] numbersToProcess) {
    int[] possibleNumbers = new int[100];
    Map<Integer, Integer> result = new HashMap<Integer, Integer>();

    for (int i = 0; i < numbersToProcess.length; ++i) {
      possibleNumbers[numbersToProcess[i]] = possibleNumbers[numbersToProcess[i]] + 1;
      result.put(numbersToProcess[i], possibleNumbers[numbersToProcess[i]]);
    }

    return result;
}

public Map<Integer, Integer> countOccurrence(int[] numbersToProcess) { int[] possibleNumbers = new int[100]; Map<Integer, Integer> result = new HashMap<Integer, Integer>(); for (int i = 0; i < numbersToProcess.length; ++i) { possibleNumbers[numbersToProcess[i]] = possibleNumbers[numbersToProcess[i]] + 1; result.put(numbersToProcess[i], possibleNumbers[numbersToProcess[i]]); } return result; }

答案 9 :(得分:0)

有几种方法可以提供帮助,但这是一种用于循环的方法。

import java.util.Arrays;

public class one_dimensional_for {

private static void count(int[] arr) {

    Arrays.sort(arr);

    int sum = 0, counter = 0;

    for (int i = 0; i < arr.length; i++) {
        if (arr[0] == arr[arr.length - 1]) {
            System.out.println(arr[0] + ": " + counter + " times");
            break;
        } else {
            if (i == (arr.length - 1)) {
                sum += arr[arr.length - 1];
                counter++;
                System.out.println((sum / counter) + " : " + counter
                        + " times");
                break;
            } else {
                if (arr[i] == arr[i + 1]) {
                    sum += arr[i];
                    counter++;
                } else if (arr[i] != arr[i + 1]) {
                    sum += arr[i];
                    counter++;
                    System.out.println((sum / counter) + " : " + counter
                            + " times");
                    sum = 0;
                    counter = 0;
                }
            }
        }
    }
}

public static void main(String[] args) {
    int nums[] = { 1, 1, 1, 1, 2, 2, 2, 3, 3, 4, 5, 5, 5, 5, 6 };
    count(nums);
}

}

答案 10 :(得分:0)

这是我在Python中使用的一个简单脚本,但它可以很容易地进行调整。没什么好看的。

def occurance(arr):
  results = []
  for n in arr:
      data = {}
      data["point"] = n
      data["count"] = 0
      for i in range(0, len(arr)):
          if n == arr[i]:
              data["count"] += 1
      results.append(data)
  return results

答案 11 :(得分:0)

你可以找到使用简单技术的HashMap

public class HashMapExample {
    public static void main(String[] args) {
        stringArray();          
    }
public static void stringArray()
{
    String[] a = {"name1","name2","name3","name4", "name5"};

    Map<String, String> hm = new HashMap<String, String>();
    for(int i=0;i<a.length;i++)
    {
    String bl=(String)hm.get(a[i]);
    if(bl==null)
    {
        hm.put(a[i],String.valueOf(1));
    }else
    {
        String k=hm.get(a[i]);
        int j=Integer.valueOf(k);
        hm.put(a[i],String.valueOf(j+1));
    }

    }
    //hm.entrySet();
    System.out.println("map elements are "+hm.toString());
}

}

答案 12 :(得分:0)

//使用Hashset或地图或Arraylist的答案

public class Count {
    static String names[] = {"name1","name1","name2","name2", "name2"};
    public static void main(String args[]) {

        printCount(names);

    }

    public static void printCount(String[] names){

        java.util.Arrays.sort(names);
        int n = names.length, c;
        for(int i=0;i<n;i++){
            System.out.print(names[i]+" ");
        }
        System.out.println();
        int result[] = new int[n];
        for(int i=0;i<n;i++){
            result[i] = 0;
        }

        for(int i =0;i<n;i++){
            if (i != n-1){
                for(int j=0;j<n;j++){
                    if(names[i] == names[j] )
                        result[i]++;
                }
            }
            else if (names[n-2] == names[n-1]){
            result[i] = result[i-1];
         }

         else result[i] = 1;
        }
        int max = 0,index = 0;
        for(int i=0;i<n;i++){
         System.out.print(result[i]+"     ");
            if (result[i] >= max){
                max = result[i];
                index = i;
            }

        }
    }
}

答案 13 :(得分:0)

您可以使用以下示例中给出的哈希映射:

import java.util.HashMap;
import java.util.Set;

/**
 * 
 * @author Abdul Rab Khan
 * 
 */
public class CounterExample {
    public static void main(String[] args) {
        String[] array = { "name1", "name1", "name2", "name2", "name2" };
        countStringOccurences(array);
    }

    /**
     * This method process the string array to find the number of occurrences of
     * each string element
     * 
     * @param strArray
     *            array containing string elements
     */
    private static void countStringOccurences(String[] strArray) {
        HashMap<String, Integer> countMap = new HashMap<String, Integer>();
        for (String string : strArray) {
            if (!countMap.containsKey(string)) {
                countMap.put(string, 1);
            } else {
                Integer count = countMap.get(string);
                count = count + 1;
                countMap.put(string, count);
            }
        }
        printCount(countMap);
    }

    /**
     * This method will print the occurrence of each element
     * 
     * @param countMap
     *            map containg string as a key, and its count as the value
     */
    private static void printCount(HashMap<String, Integer> countMap) {
        Set<String> keySet = countMap.keySet();
        for (String string : keySet) {
            System.out.println(string + " : " + countMap.get(string));
        }
    }
}

答案 14 :(得分:0)

使用哈希表,流和集合计数字符串的出现

@Bean
public Step step1() throws Exception {
    log.info("!!!  step1 !!");

    return this.stepBuilderFactory.get("step1")
            .<Position, Position> chunk(100)
            .reader(read())
            .processor(  (ItemProcessor) asyncItemProcessor() )
            .writer( asyncItemWriter() )
            .allowStartIfComplete(true)
            .build();
}

}

答案 15 :(得分:0)

public class Main
{
    public static void main(String[] args) {
        
        String[] a ={"name1","name1","name2","name2", "name2"};
        for (int i=0;i<a.length ;i++ )
        {
            int count =0;
            int count1=0;
            for(int j=0;j<a.length;j++)
            {
                if(a[i]==a[j])
                {
                    count++;
                    
                }
            }
            for(int j=i-1;j>=0 ;j--)
            {
                if(a[i]==a[j])
                {
                    count1++;
                }
            }
            if(count1 ==0)
            {
                System.out.println(a[i]+" occurs :"+count);
            }
        }
    }
}

答案 16 :(得分:-1)

您可以使用HashMap,其中Key是您的字符串和值 - 计数。

答案 17 :(得分:-2)

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class MultiString {

    public HashMap<String, Integer> countIntem( String[] array ) {

        Arrays.sort(array);
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        Integer count = 0;
        String first = array[0];
        for( int counter = 0; counter < array.length; counter++ ) {
            if(first.hashCode() == array[counter].hashCode()) {
                count = count + 1;
            } else {
                map.put(first, count);
                count = 1;
            }
            first = array[counter];
            map.put(first, count);
        }

        return map;
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String[] array = { "name1", "name1", "name2", "name2", "name2",
                "name3", "name1", "name1", "name2", "name2", "name2", "name3" };

        HashMap<String, Integer> countMap = new MultiString().countIntem(array);
        System.out.println(countMap);
    }
}



Gives you O(n) complexity.