Java来计算字符串的顺序

Java来计算字符串的顺序,java,arrays,hashmap,set,Java,Arrays,Hashmap,Set,我正在寻找一种方法来对字符串中的一系列单词进行分组和计数 范例 String = " 15, 15 , 15 , 2 , 2 , 0 " 我正在寻找的输出是 15(3) 2(2) 0(1) 换句话说,它必须是未排序的,所以我知道序列将是3x15,然后是2x2和0x1 因此它将有一个类似15(3)2(2)0(1) 我试试这个代码 String str = "15|15|15|11|15|15|15|15|15|12|"; String[] splitStr = str.spl

我正在寻找一种方法来对字符串中的一系列单词进行分组和计数

范例

String  = " 15, 15 , 15 , 2 , 2 , 0 "
我正在寻找的输出是

15(3)
2(2)
0(1)
换句话说,它必须是未排序的,所以我知道序列将是3x15,然后是2x2和0x1

因此它将有一个类似
15(3)2(2)0(1)

我试试这个代码

String str = "15|15|15|11|15|15|15|15|15|12|";
        String[] splitStr = str.split("\\|");

        Map<String, Integer> wordCount = new HashMap<>();
        for (String word : splitStr) {
            if (wordCount.containsKey(word)) {
                // Map already contains the word key. Just increment it's count by 1
                wordCount.put(word, wordCount.get(word) + 1);
            } else {
                // Map doesn't have mapping for word. Add one with count = 1
                wordCount.put(word, 1);
            }
        }


        for (Entry<String, Integer> entry : wordCount.entrySet()) {
            System.out.println(entry.toString().replaceAll("=","(")+")");
        }
String str=“15 | 15 | 15 | 11 | 15 | 15 | 15 | 15 | 12 |”;
字符串[]splitStr=str.split(“\\\\”);
Map wordCount=new HashMap();
for(字符串字:splitStr){
if(wordCount.containsKey(word)){
//映射已经包含单词键。只需将其计数增加1
wordCount.put(word,wordCount.get(word)+1);
}否则{
//映射没有word的映射。请添加计数为1的映射
wordCount.put(word,1);
}
}
for(条目:wordCount.entrySet()){
System.out.println(entry.toString().replaceAll(“=”,“(”+”));
}
但产出变得越来越高

15(8) 11(1) 12(1)

我正在寻找像这样的输出

15(3) 11(1) 15(5)
12(1)

这看起来像是家庭作业,不是吗

如何拆分字符串
StringTokenizer
沿分隔符:空格和逗号;或
String.split
,但它使用正则表达式。
如何分组和计数
HashMap
将数字作为键,并将其计数作为值。
如何保持插入密钥的顺序:
LinkedHashMap

回复:更新 看起来你已经得到了上面的信息。你的新要求

“如果一个数字出现多次,则应单独计算”

这使得它有点复杂,Java内置类无法做到这一点

一个小指南:您基本上需要找到序列并计算有多少相同的数字。通过上一个和当前(或当前和下一个,取决于您的思维方式)的不同,您将知道序列边界在哪里。如果它们是相同的,那么你是中间序列,所以只要数一数。如果它们不同,你需要记下新的号码

在代码中实现以下思想:

15|15|15|11|15|15|15|15|15|12|
^ 15, that's new, we have 1
15|15|15|11|15|15|15|15|15|12|
   ^ 15 again, we have 2
15|15|15|11|15|15|15|15|15|12|
      ^ 15 again, we have 3
15|15|15|11|15|15|15|15|15|12|
         ^ 11, that's new. So 15(3). 11, we have 1
15|15|15|11|15|15|15|15|15|12|
            ^ 15, that's new. So 11(1). 15, we have 1
15|15|15|11|15|15|15|15|15|12|
               ^ 15 again, we have 2
15|15|15|11|15|15|15|15|15|12|
                  ^ 15 again, we have 3
15|15|15|11|15|15|15|15|15|12|
                     ^ 15 again, we have 4
15|15|15|11|15|15|15|15|15|12|
                        ^ 15 again, we have 5
15|15|15|11|15|15|15|15|15|12|
                           ^ 12, that's new. So 15(5). 12, we have 1
15|15|15|11|15|15|15|15|15|12|
                              ^ finished so let's not forget the last one 12(1)

如果字符串是这样的=15,15,15,11,15,15,15,15,12,我希望输出将变成15(3)11(1)15(5)12(1),即使15号出现了2次。那么这也应该是一个问题,还有你期望的是什么,以及你是如何被卡住的。另外,不要混用分隔符,只使用一个符号。我已经用我使用的示例代码编辑了这个问题。我刚才回答说:)