[英]How to split a string into a map with a list of values?
I am a bit stuck with my application, and I am not quite sure what to search for. 我的应用程序有点卡住,我不确定要搜索什么。 So I am hoping someone here may help me out. 所以我希望这里有人可以帮助我。
I have a list of String
s, that looks like this: 我有一个String
列表,看起来像这样:
Cake;carrot
Cake;apple
Cake;spicy
Pizza;pepperoni
Pizza;mozzarella
... and so on. ... 等等。 I want to put this data into a Map<String, List<String>>
, where Cake
and Pizza
will make up the keys in my Map
. 我想将此数据放入Map<String, List<String>>
,其中Cake
和Pizza
将构成Map
的键。 Having [carrot, apple, spicy]
as Cake
's values, and [pepperoni, mozzarella]
as Pizza
's values. 以[carrot, apple, spicy]
为Cake
的值,并以[pepperoni, mozzarella]
为Pizza
的值。
How may I achieve this? 我该如何实现? Thanks in advance for any help. 在此先感谢您的帮助。
Just iterate over your list using String.split()
只需使用String.split()
遍历您的列表
ArrayList<String> myList;
HashMap<String, List<String>> myMap = new HashMap<>();
for(String s : myList)
{
String[] split = s.split(";");
List<String> bucket = myMap.get(split[0]);
if(bucket == null)
{
bucket = new ArrayList<String>();
myMap.put(split[0], bucket);
}
bucket.add(split[1]);
}
You can try this, use a hashmap, store consecutive strings with 您可以尝试使用哈希表,使用 (space) as the delimiter, finally split the string when you want it as a list (空格)作为定界符,最后在您希望将其作为列表使用时拆分字符串
//Assuming your list to be the variable 'list'
HashMap<String,String> hm = new HashMap<>();
for(val : list){
String st[] = val.split(";");
if(hm.get(st[0])==null){
hm.put(st[0],st[1]);
}
else{
hm.put(st[0],hm.get(st[0])+" "+st[1]);
}
}
when You want the string array of say pizza
back then 当您想要返回说pizza
的字符串数组时
String pizz[] = (hm.get("pizza")).split(" ");
pizz[]
will have your array, cheers! pizz[]
将为您pizz[]
!
public static void main(String[] args) {
List<String> data = new ArrayList<String>();
Map<String, List<String>> finalData = new HashMap<String,List<String>>();
data.add("Cake;carrot");
data.add("Cake;apple");
data.add("Cake;spicy");
data.add("Pizza;pepperoni");
data.add("Pizza;mozzarella");
for (String dataString : data) {
List<String> temp = null;
if (finalData.get(dataString.split(";")[0]) == null) {
temp = new ArrayList<String>();
temp.add(dataString.split(";")[1]);
finalData.put(dataString.split(";")[0], temp);
} else {
temp = finalData.get(dataString.split(";")[0]);
temp.add(dataString.split(";")[1]);
finalData.put(dataString.split(";")[0], temp);
}
}
System.out.println(new Gson().toJson(finalData));
}
Complete working solution. 完整的工作解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.