Hashmap实现计算每个字符的出现次数

时间:2010-12-06 05:53:23

标签: java collections

下面的代码是计算每个字符的出现次数,它应该打印计数。  但是使用我试过的代码我只得到1我不知道我应该做的改变。请帮帮我。

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

class Count_CharMap {
public static void main(String[] args) {
    try
    {
        FileInputStream file = new FileInputStream("D:\\trial.txt");
        DataInputStream dis = new DataInputStream(file);
        BufferedReader br = new BufferedReader(new InputStreamReader(dis));
        String Contents="";
        String str="";

        while ((Contents = br.readLine()) != null) {
            str+=Contents;
        }

        char[]char_array =str.toCharArray();
        int count = 0;
        char ch = char_array[count];
        Map<Character,Integer> charCounter=new HashMap<Character,Integer>();
        for(int i=0;i<str.length();i++)
        {
            if(charCounter.containsKey(char_array[i]))
            {
                charCounter.put(ch, charCounter.get(ch)+1);
            } 
            else
            {
                charCounter.put(ch, 1);
            }
       }

       for(Character key:charCounter.keySet())
       {
           System.out.println(key+""+charCounter.get(key));
       }
    } 
    catch(IOException e1){
        System.out.println(e1);
    }
    }
}

实际输出应该是这样的 如果我在trial.txt中有abcdabc,它应该打印2 b 2c 2 d 1.

10 个答案:

答案 0 :(得分:10)

在每次执行循环时,您将char ch设置为相同的字符。

应该是:

ch = char_array[i]; 
if(charCounter.containsKey(ch)){
     charCounter.put(ch, charCounter.get(ch)+1);
}
else
{
    charCounter.put(ch, 1);
}

在for循环中。

答案 1 :(得分:5)

Java 8流:

Map<String, Long> map = 
    Arrays.stream(string.split("")).
    collect(Collectors.groupingBy(c -> c, Collectors.counting()));

番石榴HashMultiset

Multiset<Character> set = HashMultiset.create(Chars.asList("bbc".toCharArray()));
assertEquals(2, set.count('b'));

答案 2 :(得分:3)

Hai All下面的代码是计算每个字符的出现次数,它应该打印计数。可能对你有所帮助。谢谢你的光临

package com.corejava;

import java.util.Map;
import java.util.TreeMap;

public class Test {
    public static void main(String[] args) {

        String str = "ramakoteswararao";

        char[] char_array = str.toCharArray();

        System.out.println("The Given String is : " + str);

    Map<Character, Integer> charCounter = new TreeMap<Character, Integer>();

        for (char i : char_array) {

    charCounter.put(i,charCounter.get(i) == null ? 1 : charCounter.get(i) + 1);

        }

    for (Character key : charCounter.keySet()) {
  System.out.println("occurrence of '" + key + "' is  "+ charCounter.get(key));
        }

    }

}

答案 3 :(得分:1)

import java.util.HashMap;
import java.util.Map;
...
Map<String, Integer> freq = new HashMap<String, Integer>();
...
int count = freq.containsKey(word) ? freq.get(word) : 0;
freq.put(word, count + 1);

答案 4 :(得分:0)

在for循环中

  

ch = char_array[i];
charCounter.put(charCounter.contains(ch)?charCounter.get(ch)+1:1);

答案 5 :(得分:0)

import java.util.TreeMap;

public class OccuranceDemo {
    public static void main(String[] args) {
        TreeMap<String , Integer> mp=new TreeMap();
        String s="rain rain go away";
        String[] arr = s.split(" ");
        int length=arr.length;
        for(int i=0;i<length;i++)
       {
         String h = arr[i];
        mp.put(h, mp.get(h)==null?1:mp.get(h)+1);
    }
    System.out.println(mp.get("go"));
  }
}

答案 6 :(得分:0)

    String str=new String("aabbbcddddee");
    char[] ch=str.toCharArray();
    HashMap<Character,Integer> hm=new HashMap<Character,Integer>();
    for(char ch1:ch)
    {

        if(hm.containsKey(ch1))
        {
            hm.put(ch1,hm.get(ch1)+1);
        }
        else
        {
            hm.put(ch1,1);
        }
    }

    Set s1=hm.entrySet();
    Iterator itr=s1.iterator();

    while(itr.hasNext())
    {
        Map.Entry m1=(Map.Entry)itr.next();
        System.out.println(m1);
    }

答案 7 :(得分:0)

import java.util.*;

public class Test {
    public static void main(String[] args) {

        String str = "STACKOVERFLOW";

        char[] char_array = str.toCharArray();

        System.out.println("The Given String is : " + str);

    Map<Character, Integer> charCounter = new TreeMap<Character, Integer>();

        for (char i : char_array) {

    charCounter.put(i,charCounter.get(i) == null ? 1 : charCounter.get(i) + 1);

        }

    for (Character key : charCounter.keySet()) {
  System.out.println("occurrence of '" + key + "' is  "+ charCounter.get(key));
        }

    }

}

答案 8 :(得分:0)

public void mapPractices(){

    Map<Character, Integer> map = new HashMap<>();
    String dataString = "!@#$%^&*()__)(*&^%$#@!@#$%^&*(*&^%$#@!@#$%^&*()(*&^%$#@!@#$%^&*()(*&^%$#@!@#$%^&*()(*&^%$#";
    for (int i = 0; i < dataString.length(); i++) {

        char charAt = dataString.charAt(i);

        if (map.containsKey(charAt)) {
            int val = map.get(charAt);
            map.put(charAt, val+1);

        } else {

            map.put(charAt, +1);
        }

    }
    System.out.println("Characters ant the string=" + map);

}

答案 9 :(得分:0)

一个lambda单缸纸
修复了老式解决方案中的错误之后,以下是lambda中具有相同功能的替代解决方案:

Map<Character,Long> counts =
"an example string to work with".codePoints().boxed().collect(
    groupingBy( t -> (char)(int)t, counting() ) );

得到:{ =5, a=2, e=2, g=1, h=1, i=2, k=1, l=1, m=1, n=2, o=2, p=1, r=2, s=1, t=3, w=2, x=1}
您可以获取特定字符的编号,例如。 't'由:
counts.get( 't' )

(出于病态的好奇心,我还编写了一个lambda解决方案,以找出我的解决方案有多慢,最好是从拥有10行解决方案的人那里找到。)