如何在文本文件中检索某些字符串并根据字符串中的元素排序?

时间:2019-04-19 08:41:22

标签: java sorting hashset

我正在尝试显示txtfile中的元素列表,然后根据每个记录的日期对列表进行排序。我已经使用哈希集完全加载txtfile,并且可以正常工作。

主要问题是我似乎找不到一种方法来根据每个记录下包含的日期对txt文件和每个记录进行排序。

btnPrintList.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {

// File path & name

Path path = Paths.get(System.getProperty("user.dir")).resolve("vehicle.txt");

try {
   BufferedReader reader = new BufferedReader(new 
   FileReader(path.toFile()));

   Set<String> carsPrint = new HashSet<>();

    String line = reader.readLine();
      while (line != null) {                 
            System.out.println("processing line: " + line);

        if (line.trim().contains("-")) {
          String[] words = line.split("");
                    }

        if (!line.trim().equals("")) {
          String[] words = line.split("");

                    }

        line = reader.readLine();

            }

        } 
              catch (IOException e1) {
        block
           e1.printStackTrace();
                }
            }

        });

这是要引用的文本文件

a, Honda Jazz, Hatchback, grey, 20000, none, manual, 8000, 2018-09-01, 2018-10-04,
b, Mercedes Citan, Van, small, white, 35000, front damage, manual, 9500, 2018-11-04,
c, Ford Transit, Van, small, black, 60000, none, automatic, 7300, 2018-11-01,
d, Lexus IS, Saloon, white, 23000, indent on passenger door, automatic, 18100, 2019-01-02,
e, Lexus IS, Saloon, dark blue, 6000, none, manual, 26100, 2018-10-04, 2018-10-14,
f, Mercedes Citan, Van, small, white, 35900, front windscreen damage, automatic, 10000, 2018-08-04,
g, Lexus NX, SUV, dark blue, 12000, none, automatic, 31000,
h, Ford SMax, MPV, red, 70000, none, manual, 11000, 2017-01-13,
i, Vauxhall Movano, Van, large, white, 60000, rear windscreen damage, manual, 5000, 2019-01-10, 2019-03-01,
j, Vauxhall Insignia, Saloon, green, 45000, none, automatic, 10800, 2018-08-10, 2019-03-05,
k, Vauxhall Insignia, Saloon, red, 40000, none, manual, 10200, 2018-08-10,
l, Vauxhall Movano, Van, large, silver, 60000, none, automatic, 8800,
m, BMW 3, Saloon, black, 49000, door damage, manual, 9500, 2019-03-01, 2019-03-05,
n, Ford SMax, MPV, red, 70000, none, automatic, 3800,
o, Mercedes EClass, Coupe, yellow, 25000, none, automatic, 10400, 2018-03-08, 2019-03-02,
p, Jaguar FType, Coupe, silver, 3000, none, automatic, 52000, 2018-03-01,

1 个答案:

答案 0 :(得分:1)

根据定义,哈希集结构无法排序。它不保证集合的迭代顺序。特别是,它不能保证顺序会随着时间的推移保持恒定。 (来自Documentation

但是您可以改用ArrayList:

List<?> sortedCarsPrint  = new ArrayList<>(carsPrint);
sortedCarsPrint.sort((o1,o2) -> o1.getDateTime().compareTo(o2.getDateTime()));