Java 将字符串存储到具有引用的hashmap中
我有一个返回某种字符串的方法。我想在HashMap中存储单个单词的出现次数Java 将字符串存储到具有引用的hashmap中,java,string,sorting,split,hashmap,Java,String,Sorting,Split,Hashmap,我有一个返回某种字符串的方法。我想在HashMap中存储单个单词的出现次数 public static void main(String[] args) { String s = "{link:hagdjh, matrics:[{name:apple, value:1},{name:jeeva, value:2},{name:abc, value:0}]}"; String[] strs = s.split("matrics"); System.
public static void main(String[] args) {
String s = "{link:hagdjh, matrics:[{name:apple, value:1},{name:jeeva, value:2},{name:abc, value:0}]}";
String[] strs = s.split("matrics");
System.out.println("Substrings length:" + strs.length);
for (int i = 0; i < strs.length; i++) {
System.out.println(strs[i]);
}
}
我应该如何进行
我知道如何使用HashMaps。在这种情况下,我的问题是我不知道如何解析给定的字符串并存储单词及其出现次数。string regex=“\\{name:(.*),value:(\\d+\\}”;
String regex = "\\{name:(.*), value:(\\d+)\\}";
HashMap<String, Integer> link = new HashMap<>();
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
String found = matcher.group(1);
String number = matcher.group(2);
link.put(found, Integer.parseInt(number));
}
HashMap link=newhashmap();
Pattern=Pattern.compile(regex);
匹配器匹配器=模式匹配器;
while(matcher.find()){
找到的字符串=matcher.group(1);
字符串编号=匹配器组(2);
link.put(find,Integer.parseInt(number));
}
看起来您的数据是JSON格式的
如果保证为JSON格式,则可以使用JSON解析库对其进行解析,然后以方便的方式分析矩阵数据(代码如下)
如果数据不能保证为JSON格式,您可以使用正则表达式来帮助您解析它,如Reza soumi的回答所示
import org.json.JSONObject;
import org.json.JSONArray;
import java.util.HashMap;
String s = "{link:hagdjh, matrics:[{name:apple, value:1},{name:jeeva, value:2},{name:abc, value:0}]}";
JSONObject obj = new JSONObject(s);
JSONArray matrics = obj.getJSONArray("matrics");
System.out.println(matrics);
HashMap<String, Integer> matricsHashMap = new HashMap<String, Integer>();
for (int i=0;i < matrics.length();i++){
JSONObject matric = matrics.getJSONObject(i);
System.out.println("Adding matric: " + matric + " to hash map");
String matricName = matric.getString("name");
Integer matricValue = Integer.valueOf(matric.getInt("value"));
matricsHashMap.put(matricName, matricValue);
}
System.out.println(matricsHashMap);
import org.json.JSONObject;
导入org.json.JSONArray;
导入java.util.HashMap;
字符串s=“{link:hagdjh,matrics:[{name:apple,value:1},{name:jeeva,value:2},{name:abc,value:0}]}”;
JSONObject obj=新的JSONObject;
JSONArray matrics=obj.getJSONArray(“matrics”);
系统输出打印LN(矩阵);
HashMap matricsHashMap=新HashMap();
对于(int i=0;i
试试这个:
import static java.lang.System.err;
import static java.lang.System.out;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toMap;
/**
* Counting the words in a String.
*/
public class CountWordsInString
{
/*-----------*\
====** Constants **========================================================
\*-----------*/
/**
* An empty array of {@code ${type_name}} objects.
*/
public static final String INPUT = "{link:https://www.google.co.in/, matrics:[{name:apple, value:1},{name:graph, value:2},{name:abc, value:0}]}";
/*---------*\
====** Methods **==========================================================
\*---------*/
/**
* The program entry point.
*
* @param args The command line arguments.
*/
public static void main( final String... args )
{
try
{
final var result = stream( INPUT.split( "\\W+" ) )
.filter( s -> !s.isBlank() )
.filter( s -> !s.matches( "\\d*" ) )
.collect( groupingBy( s -> s ) )
.entrySet()
.stream()
.collect( toMap( k -> k.getKey(), v -> Long.valueOf( v.getValue().size() ) ) );
out.println( result.getClass() );
for( final var entry : result.entrySet() )
{
out.printf( "'%s' occurred %d times%n", entry.getKey(), entry.getValue() );
}
}
catch( final Throwable t )
{
//---* Handle any previously unhandled exceptions *----------------
t.printStackTrace( err );
}
} // main()
}
// class CountWordsInString
坦白说,这不是最明显的解决办法,但我也想从中得到一些乐趣
INPUT.split(\\W+”)
提供字符串中的单词,但也提供数字和开头的“空”单词
“空”字在第一个filter()
语句中被删除,数字与第二个一起
第一个collect(groupingBy())
提供了一个HashMap
,因此我必须在以下步骤中将其转换为HashMap
(基本上是第二个collect(groupingBy())
)
也许有一个更有效的解决方案,或者更优雅的解决方案,或者两者兼而有之,更高效、更优雅的解决方案……但它的工作原理与预期相符,我从中得到了一些乐趣
输出为:
class java.util.HashMap
'apple' occurred 1 times
'matrics' occurred 1 times
'abc' occurred 1 times
'in' occurred 1 times
'www' occurred 1 times
'name' occurred 3 times
'link' occurred 1 times
'google' occurred 1 times
'https' occurred 1 times
'co' occurred 1 times
'value' occurred 3 times
'graph' occurred 1 times
@ArvindKumarAvinash:示例字符串类似于JSON字符串并不意味着所有输入都是JSON——因此JSON解析器可能不是解决方案……我的建议是,您应该通过单独设置class@tquadrat-我同意你的看法。我在这里发布了一个解决方案,任务不是计算任意字符串中的单词,任务是解析一个(JSON?)字符串,该字符串包含一些单词及其出现(可能在不同的文本中)我建议相应地更新问题的文本…
apple = 1
jeeva = 2
abc = 0
import static java.lang.System.err;
import static java.lang.System.out;
import static java.util.Arrays.stream;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toMap;
/**
* Counting the words in a String.
*/
public class CountWordsInString
{
/*-----------*\
====** Constants **========================================================
\*-----------*/
/**
* An empty array of {@code ${type_name}} objects.
*/
public static final String INPUT = "{link:https://www.google.co.in/, matrics:[{name:apple, value:1},{name:graph, value:2},{name:abc, value:0}]}";
/*---------*\
====** Methods **==========================================================
\*---------*/
/**
* The program entry point.
*
* @param args The command line arguments.
*/
public static void main( final String... args )
{
try
{
final var result = stream( INPUT.split( "\\W+" ) )
.filter( s -> !s.isBlank() )
.filter( s -> !s.matches( "\\d*" ) )
.collect( groupingBy( s -> s ) )
.entrySet()
.stream()
.collect( toMap( k -> k.getKey(), v -> Long.valueOf( v.getValue().size() ) ) );
out.println( result.getClass() );
for( final var entry : result.entrySet() )
{
out.printf( "'%s' occurred %d times%n", entry.getKey(), entry.getValue() );
}
}
catch( final Throwable t )
{
//---* Handle any previously unhandled exceptions *----------------
t.printStackTrace( err );
}
} // main()
}
// class CountWordsInString
class java.util.HashMap
'apple' occurred 1 times
'matrics' occurred 1 times
'abc' occurred 1 times
'in' occurred 1 times
'www' occurred 1 times
'name' occurred 3 times
'link' occurred 1 times
'google' occurred 1 times
'https' occurred 1 times
'co' occurred 1 times
'value' occurred 3 times
'graph' occurred 1 times