gpt4 book ai didi

java - 将两个逗号分隔的字符串转换为 Map

转载 作者:行者123 更新时间:2023-12-01 10:00:26 37 4
gpt4 key购买 nike

我有两个逗号分隔的字符串。我希望通过按索引绑定(bind)值将这些值放入映射中。一种方法是使用以下示例:

package com.test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StringToMap {

public static void main(String[] args) {
String s1 = "1, 2, 3";
String s2 = "a, b, c";
Map<String, String> m = new HashMap<String, String>();

List<String> s1List = new ArrayList<String>(Arrays.asList(s1.split(",")));
List<String> s2List = new ArrayList<String>(Arrays.asList(s2.split(",")));

for (int i = 0; i < s1List.size(); i++) {
m.put(s1List.get(i).trim(), s2List.get(i).trim());
}

System.out.println(m);
}
}

结果是:{3=c, 2=b, 1=a}。还有其他有效/最佳的方法吗?

最佳答案

你对此有何看法?

public static void main(String[] args) {
String s1 = "1, 2, 3";
String s2 = "a, b, c";
Map<String, String> m = new HashMap<String, String>();
String s1List [] = s1.split(",");
String s2List [] = s2.split(",");
for (int i = 0; i < s1List.length && i < s2List.length; i++) {
m.put(s1List[i].trim(), s2List[i].trim());
}
System.out.println(m);
}

关于java - 将两个逗号分隔的字符串转换为 Map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36857896/

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