英文:
Getting Data from Arraylist and input into put method of LinkedHashMap
问题
public Map<String, String> convertMap(ArrayList<String> Data){
Map<String, String> myLinkedHashMap = new LinkedHashMap<String, String>();
myLinkedHashMap.put("1", "first");
myLinkedHashMap.put("2", "second");
myLinkedHashMap.put("3", "third");
return myLinkedHashMap;
}
I am stucked on getting out the respective information from the ArrayList
Lets say Arraylist
Name: John
Age: 20
Gender: Male
I wan to replace 'Name' at the "1" Column , and 'John' at the "First" Column.
Can anyone kindly guide me on this issue?
<details>
<summary>英文:</summary>
i have this function below which takes in a arraylist of Strings and return a LinkedHashMap. I plan to use this linkedhashmap to write into a textfile subsequently.
public Map<String,String> convertMap(ArrayList<String> Data){
Map<String,String> myLinkedHashMap = new LinkedHashMap<String, String>();
myLinkedHashMap.put("1", "first");
myLinkedHashMap.put("2", "second");
myLinkedHashMap.put("3", "third");
return myLinkedHashMap;
}
I am stucked on getting out the respective information from the ArrayList<String> Data in order to use the put method to insert it into a linkedhashmap.
Lets say Arraylist<String> Data contains:
Name: John
Age: 20
Gender: Male
I wan to replace 'Name' at the "1" Column , and 'John' at the "First" Column.
Can anyone kindly guide me on this issue ?
</details>
# 答案1
**得分**: 0
让我们假设你的 ArrayList `list` 包含:
{"Name: John", "Age: 20", "Gender: Male"}
然后你可以循环遍历 ArrayList 中的每个元素,以获取每个单独的字符串。然后,你可以将字符串拆分成两部分,然后将这两部分都放入你的 HashMap 中:
for (String string : list) {
String[] result = string.split(":", 2); // "Name: John"
map.put(result[0], result[1].trim()); // 变为:"Name", "John"
}
我在第二个字符串上使用了 `trim()` 来移除任何多余的空格。
**注意:**
这并不是很优雅的解决方案。这只允许特定格式的字符串,但如果它们确保是符合格式的,那么这个方法会起作用。
<details>
<summary>英文:</summary>
Let's say your ArrayList `list` contains:
{"Name: John", "Age: 20", "Gender: Male"}
You then could loop trough every element in your ArrayList to get every single string. You could then split the string into 2, then put both parts into your HashMap:
for(String string : list) {
String[] result = string.split(":", 2); // "Name: John"
map.put(result[0], result[1].trim()); // becomes: "Name", "John"
}
I use `trim()` on the second String to remove any excess whitespaces.
**Note:**
This is not pretty. This only allows Strings in a certain format, but will do the job if they 100% are.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论