![](/img/trans.png)
[英]How to store the parts of Strings in dictionary after splitting it in java
[英]How to store the parts of the string in dictionary in java
我想將拆分為兩部分的字符串存儲在字典的第0和第1位。 假設值是frequency:50,那么頻率在字典中將位於第0位,而50將位於第1位,以下是相同的C#代碼
data_dictionary = data.Split(',')
.ToDictionary(item => item.Split(':')[0], item => item.Split(':')[1]);
我想要在java中的解決方案,任何幫助將不勝感激
String delimiter = ",";
temp = str.split(delimiter); //str being your "long" string
for ( int i =0; i < temp.length ; i++ ){
delimiter = ":";
temp2 = temp[i].split(delimiter);
for(int k =0; k < temp2.length ; k++)
System.out.println(temp2[k]); //here your code
}
將打印:
frequency
50
而且,無論您想使用它們做什么,都將把子字符串存儲在:
temp2[0] = frequency //just for this example
temp2[1] = 50
您必須在我編寫的代碼的最后一行進行處理,因為temp2
的值將替換為每個以','
分隔的子字符串。
抱歉,沒有閉包,Java無法達到C#代碼的優雅水平。 您可能會發現使用匿名類對此進行近似的東西,但這並不是真正值得的。 因此,只需編寫一個常規循環, put
內容放入HashMap<String, String>
。 您可以使用String#split(regex)
以相同的方式拆分字符串。
int delim = data.indexOf(':');
System.out.println( data.substring(0,delim) ); //frequency
System.out.println( data.substring(delim+1) ); //50
如果您想要一些閉包式的東西,那么它可能具有如下功能簽名:
interface KeyPairFunctor<T, K, V> {
Pair<K, V> getKeyValuePair(T item);
}
public static <T, K, V> Map<K, V> toMap(Iterable<T> items, KeyPairFunctor<T, K, V> functor) {
Map<K, V> m = new HashMap<K,V>();
for (T item : items) {
Pair<K, V> e = functor.getKeyValuePair(item);
m.put(e.getKey(), e.getValue());
}
return m;
}
public static void test() {
toMap(Arrays.asList(new String[] { "A:B" }), new KeyPairFunctor<String, String, String>() {
@Override
public Pair<String, String> getKeyValuePair(String item) {
String[] ss = item.split(":");
return new Pair(ss[0], ss[1]);
}});
}
實現Pair
被作為練習留給讀者,我敢肯定,你可以看到你如何把你的,
在第一個參數分割列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.