标签:main put 更新 string for java https empty arraylist
原链接:https://blog.csdn.net/qq_37164847/article/details/82460801
原始数组: String [] data = {"101//aaa","102//bbb","101//ccc","103//aaa","102//vvvv"};
把相同开头的,例如101,102,103开头的元素,取出来组成新的数组
String[] a1={"101//aaa","101//ccc"};
String[] a2={"102//bbb","102//vvvv"};
String[] a3={"103//aaa"};
1.方法一:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class testa {
public static void main(String[] args) {
String [] data = {"101//aaa","102//bbb","101//ccc","103//aaa","102//vvvv"};
Map<String,List<String>> map = new HashMap<>();
for (String str : data) {
String key = str.substring(0, str.indexOf("//"));
List<String> list = map.get(key);
//如果map中对应key,创建String数组,并加到map中
if(list==null||list.isEmpty()){
list = new ArrayList<>();
map.put(key,list);
}
//如果map有key对应的string数组,更新数组,为啥map没有put就更新了数组
list.add(str);
}
System.out.println(map);
}
}
打印出来:
{101=[101//aaa, 101//ccc], 102=[102//bbb, 102//vvvv], 103=[103//aaa]}
java之把一个String数组中有相同共性的元素抽取出来组成新的数组
标签:main put 更新 string for java https empty arraylist
原文地址:https://www.cnblogs.com/lwh-12345/p/13663232.html