java - 如何通过计算每个字符的出现次数将字符串转换为ArrayList?

标签 java json

我有一个输入字符串:

String str="1,1,2,2,2,1,3";

我想计算每个 id 的出现并将它们存储到列表中,并且我想要像这样的输出:

 [
  {
   "count": "3",
    "ids": "1, 2"
   }
   {
     "count": "1",
      "ids": "3"
    }
      ]

我尝试使用 org.springframework.util.StringUtils.countOccurrencesOf(input, "a"); 像这样。但数完之后并没有得到我想要的东西。

最佳答案

这会给你想要的结果。首先计算每个字符的出现次数,然后按计数将每个字符分组到新的 HashMap<Integer, List<String>> 中。 。

这是一个工作示例:

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

public class Test {

public static void main(String[] args) {

    String str = "1,1,2,2,2,1,3";

    String[] list = str.split(",");
    HashMap<String, Integer> occr = new HashMap<>();
    for (int i = 0; i < list.length; i++) {
        if (occr.containsKey(list[i])) {
            occr.put(list[i], occr.get(list[i]) + 1);
        } else {
            occr.put(list[i], 1);
        }
    }
    HashMap<Integer, List<String>> res = new HashMap<>();
    for (String key : occr.keySet()) {
        int count = occr.get(key);
        if (res.containsKey(count)) {
            res.get(count).add(key);
        } else {
            List<String> l = new ArrayList<>();
            l.add(key);
            res.put(count, l);
        }
    }

    StringBuffer sb = new StringBuffer();
    sb.append("[\n");
    for (Integer count : res.keySet()) {
        sb.append("{\n");
        List<String> finalList = res.get(count);
        sb.append("\"count\":\"" + count + "\",\n");
        sb.append("\"ids\":\"" + finalList.get(0));
        for (int i = 1; i < finalList.size(); i++) {
            sb.append("," + finalList.get(i));
        }
        sb.append("\"\n}\n");

    }
    sb.append("\n]");
    System.out.println(sb.toString());
}
}

编辑:更通用的解决方案

这是返回 HashMap<Integer,List<String>> 的方法,其中包含字符串出现的次数作为 HashMap 的键其中每个键都有一个 List<String> value 包含出现key次数的所有字符串。

public HashMap<Integer, List<String>> countOccurrences(String str, String delimiter) {
    // First, we count the number of occurrences of each string.
    String[] list = str.split(delimiter);
    HashMap<String, Integer> occr = new HashMap<>();
    for (int i = 0; i < list.length; i++) {
        if (occr.containsKey(list[i])) {
            occr.put(list[i], occr.get(list[i]) + 1);
        } else {
            occr.put(list[i], 1);
        }
    }
    /** Now, we group them by the number of occurrences,
     * All strings with the same number of occurrences are put into a list;
     * this list is put into a HashMap as a value, with the number of 
     * occurrences as a key.
     */
    HashMap<Integer, List<String>> res = new HashMap<>();
    for (String key : occr.keySet()) {
        int count = occr.get(key);
        if (res.containsKey(count)) {
            res.get(count).add(key);
        } else {
            List<String> l = new ArrayList<>();
            l.add(key);
            res.put(count, l);
        }
    }
    return res;
}

关于java - 如何通过计算每个字符的出现次数将字符串转换为ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42897301/

相关文章:

java - 使用 File.listFiles() 时出现 IntelliJ "may cause NullPointerException"警告

python - 使用pyarrow和json.dump将json文件保存到hdfs中

javascript - SAPUI5 设置JSON模型

java - Java正则表达式向后引用两位数

javascript - 带有对象的 fs.writefile 返回 [object object]

json - 使用 map 和列表列将非规范化表导出到cassandra表

json - 网络响应中同一 json 对象的不同 key 类型

java - 在 Java 中实现抽象方法时是否应该添加 @Override 注释?

java.lang.ClassCastException : java. lang.Boolean 无法转换为 java.util.Map

java - org.hibernate.StaleStateException : Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1