取出指定条件二维数组的子数组:
1)传入参数为 :
参数一 : String[][] sArray2 字符串二维数组
参数二 : String key 字符串
参数三 : String keyFormat 含匹配符的字符串, 如下 : %0-%1, 其中 % x含义如为:一维数据列序号为x的值。 keyFormat 可以为 %0-%1-%2,%0-%3-%8-%x......
例子如下 :对于如下二维数组 String[][] sArray2 = new String { {"1", "2", "3", "4"} , {"11", "22", "33", "44"} , {"a", "b", "c", "d"} , {"1", "2", "1.1", "2.2"}},对于 用keyFormat : %0-%1格式化后值分别为 :第一行:1-2,第二行:11-22,第三行 : a-b,第四行: 1-2
2) 请书写方法返回指定key, 满足keyFormat 的二维数组的子数组。
如以上例子的参数为key = "1-2", keyFormat = "%0-%1", 返回结果 String[][] sResult = new String[][] { {"1", "2", "3", "4"} , {"1", "2", "1.1", "2.2"} }
getSubArray(String[][] sArray2, String key, String keyFormat)
public class TestException {
public static void main(String[] args) {
String[][] sArray2 = {{"1","2","3","4"},{"11","22","33","44"},{"a","b","c","d"},{"1","2","1.1","2.2"}};
String keyFormat = "%0-%1";
String key = "1-2";
//数组转成List,注意Arrays.asList生成的是Arrays的内部类ArrayList
ArrayList<String[]> list = new ArrayList<>(Arrays.asList(sArray2));
ArrayList<String[]> newList = new ArrayList<>();
for(String[] arr:list){
List<java.lang.String> arrList = Arrays.asList(arr);
String format = format(arrList, keyFormat);
System.out.println(format);
if(format.equals(key)){
newList.add(arr);
}
}
System.out.println(Arrays.deepToString(newList.toArray()));
}
public static String format(List<String> list,String keyFormat){
Pattern pattern = Pattern.compile("%(\\d{1,})");
Matcher matcher = pattern.matcher(keyFormat);
StringBuilder sb = new StringBuilder();
while (matcher.find()){
String index = matcher.group(1);
String s = list.get(Integer.parseInt(index));
if(sb.length() == 0){
sb.append(s);
}else{
sb.append("-"+s);
}
}
return sb.toString();
}
}