java - 对子字符串内的子字符串进行排序

标签 java string comparator sortedmap

我正在查看文件名日志及其在指定日期的最后修改时间。其内容如下:

(comment:file_02389.txt,lastmodified:Wed Oct 10 19:10:49)
(comment:file_02342.txt,lastmodified:Wed Oct 10 17:16:08)
(comment:file_02315.txt,lastmodified:Wed Oct 10 18:45:12)
(comment:file_02344.txt,lastmodified:Wed Oct 10 08:31:01)

日志以单个字符串形式给出,没有换行符。我想解析字符串以查找最近修改的文件,即具有最新日期,在本例中为 file_02389.txt。每个“注释”的字符长度是恒定的,但假设将来可能会发生变化,并且如果同一文件被修改多次,文件名将不会是唯一的。

是否有最可扩展/可维护的方式来查找最新文件?执行时间和内存并不是那么重要的因素。主要关心的是初学者程序员能否理解并使用代码。

我的第一个想法是将字符串拆分为可以使用自定义比较器排序的列表。我认为这很简单,但不可扩展:

{//given String log
...
//setup
List<String> temp = Arrays.asList(log.trim().split("\\(comment\\:")); //too complex for one line?
//the first entry is blank so it must be removed else a substring() call will fail
if(temp.get(0).equals(""))
    temp.remove(0);
int period = full.get(0).indexOf('.');
int colon = full.get(0).indexOf(':');

//process
Collections.sort(temp, DATE);
return test.get(test.size()-1).substring(0, period)) //last entry is the most recent
}

public final Comparator<String> DATE = new Comparator<String>()
{
public int compare(String s1, String s2)
    {
        return s1.substring(28).compareTo(s2.substring(28));
    } 
};

它可以工作,但使用取决于行长度的子字符串和仅在这种情况下有用的比较器。我不喜欢使用 .split ,然后必须删除第一个条目,但我想避免使用真实且难以理解的正则表达式(如果这是替代方案)。将日期视为字符串而不是作为整数或日期对象进行比较似乎不可取,但可以节省代码行。

我目前使用排序映射,避免创建具有随机数字的一次性比较器,但专用映射对于我想要做的事情来说似乎相当复杂。我仍然认为这比创建一个数组用于文件名、另一个数组用于时间、然后创建第三个数组来复制时间要好,这样可以对时间数组进行排序,并将其最后一个值与副本中的相应索引进行比较。

{
...
//same setup as before
//process
//key is time, value is file name
SortedMap<String, String> map = new TreeMap<String, String>();
for(String s : temp)
    map.put(s.substring(colon+1), s.substring(0, period));
//the value to which the last key is mapped is guaranteed to be the most recent file
return map.get(map.lastKey()); //too complex for one line?
}

最佳答案

这样的东西有用吗? 基本上解析每行的日期,构建“Pair”对象的集合,以便我可以根据日期对集合进行排序。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;


public class Parse {

    /**
     * @param args
     * @throws ParseException 
     */
    public static void main(String[] args) throws ParseException {
        StringBuilder sb = new StringBuilder();
        sb.append("(comment:file_02389.txt,lastmodified:Wed Oct 10 19:10:49)").append("\n");
        sb.append("(comment:file_02342.txt,lastmodified:Wed Oct 10 17:16:08)").append("\n");
        sb.append("(comment:file_02315.txt,lastmodified:Wed Oct 10 18:45:12)").append("\n");
        sb.append("(comment:file_02344.txt,lastmodified:Wed Oct 10 08:31:01)").append("\n");

            //create a date format that can parse dates formatted in the file
        SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss");

            //read the file into an array of lines (or read one line at a time)
        String[] lines = sb.toString().split("\n");

            //create an array of pair objects to hold the line as well as the date
        List<Pair> list = new ArrayList<Pair>();


        for(int i=0;i<lines.length;i++){
                    //get the date component of the line
            String dateString = lines[i].substring(lines[i].length()-20, lines[i].length()-1);

            Pair pair = new Pair();
            pair.date = sdf.parse(dateString); 
            pair.line = lines[i];
            list.add(pair);
        }
        Collections.sort(list);
        System.out.println(list.get(list.size()-1).line);
    }
}
class Pair implements Comparable<Pair>{

    public Date date;
    public String line;

    @Override
    public int compareTo(Pair o) {
        return date.compareTo(o.date);
    }

}

关于java - 对子字符串内的子字符串进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12848454/

相关文章:

Java,使用比较器对ArrayList进行排序

java - 在 JUnit 4 中的相同测试方法下使用多个参数测试相同的异常

java - 从 Tomcat 6.0.18 升级会出现新的异常

java - 如何更改不是我在 RecycleView 中单击的项目?

java - Tabe 字段状态自动更新检查系统日期使用 mysql 和 java 中的查询

python - 获取指定URL的所有参数

java - String literal 声明但不再引用是否符合 G'ed 条件?

java - 使用哪一个 - String 或 StringBuffer 连接

java - 为什么 Comparator<Integer[]> 抛出异常?

java - 按排名和字母顺序对 IRC 用户进行排序 - Java Comparator