我试图解析声明为这样的List中元素的值:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
值如下:
a:1-2
b:3-5
但我希望一个ArrayList具有第一个数字(即1,3),而另一个具有第二个数字(即2,5)。我解决了这个问题...... Sorta:
String delims= "\t"; String delim2= ":"; String delim3= "-";
String splits2[]; String splits3[]; String splits4[];
Map<String,String> dupMap = new TreeMap<String, String>();
List<String> uniqueList = new ArrayList<String>(dupMap.values());
ArrayList<String> parsed2 = new ArrayList<String>();
ArrayList<String> parsed3 = new ArrayList<String>();
ArrayList<String> parsed3two= new ArrayList<String>();
double uniques = uniqueList.size();
for(int a=0;a<uniques;a++){
//this doesn't work like it would for an ArrayList
splits2 = uniqueList.split(delim2) ;
parsed2.add(splits2[1]);
for(int q=0; q<splits2.length; q++){
String change2 = splits2[q];
if(change2.length()>2){
splits3 = change2.split(delim3);
parsed3.add(splits3[0]);
String change3=splits3[q];
if (change3.length()>2){
splits4 = change3.split(delims);
parsed3two.add(splits4[0]);
}
}
}
}
然而,uniqueList.split不起作用,我不知道List是否有类似的功能。有什么建议吗?
答案 0 :(得分:4)
如果您知道所有数据都采用[something]:[num]-[num]
格式,则可以使用这样的正则表达式:
Pattern p = Pattern.compile("^([^:]*):([^-]*)-([^-]*)$");
// I assume this holds all the values:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
for (String src : uniqueList) {
Matcher m = p.matcher(src);
if( m.find() && m.groupCount() >= 3) {
String firstValue = m.group(1); // value to left of :
String secondValue = m.group(2); // value between : and -
String thirdValue = m.group(3); // value after -
// assign to arraylists here
}
}
我实际上并未将代码添加到特定的ArrayList
中,因为我无法从您的代码中告诉ArrayList
应该保留哪个值。
修改强>
根据Code-Guru的评论,使用String.split()
的实现将是这样的:
String pattern = "[:\\-]";
// I assume this holds all the values:
List<String> uniqueList = new ArrayList<String>(dupMap.values());
for (String src : uniqueList) {
String[] parts = src.split(pattern);
if (parts.length == 3) {
String firstValue = parts[1]; // value to left of :
String secondValue = parts[2]; // value between : and -
String thirdValue = parts[3]; // value after -
// assign to arraylists here
}
}
两种方法在效率方面几乎相同。
答案 1 :(得分:0)
据我所知,你的问题如下:
for each String in uniqueList
parse the string into a character and two integers (probably using a single call to [String.split()](http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String, int))
insert the first integer into an List
insert the second integer into another List
这是伪代码。翻译成Java是留给读者的练习。