gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:49:20 25 4
gpt4 key购买 nike

我有一个输入字符串:

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>包含出现 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 - 如何通过计算每个字符的出现次数将 String 转换为 ArrayList?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42897301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com