简体   繁体   English

Java什么数据结构?

[英]Java what data structure?

I have a file with lines like 我有一个像这样的文件

barcode date action

for example 例如

IP720H7 20130527192802 in the box

and starting from the end of the file, i want to search for the previous line that contains exact the same barcode, and take its date and action. 从文件末尾开始,我要搜索包含完全相同的条形码的上一行,并采取其日期和操作。

i will give the example below 我会在下面举例

FILE 文件

IP720H4 20130528131526  in refrigerator
IP720H4 20130528130526  in refrigerator         
IP720H2 20130528130547  in refrigerator         
20IB7   20130528130528  box             
IP720H4 20130528130530  in the box  

WANTED OUTPUT 想要的输出

IP720H4 20130528130530  in the box  FOUND  LAST IP720H4 20130528130526  in refrigerator
20IB7   20130528130528  box NOT FOUND
IP720H2 20130528130547  in refrigerator NOT FOUND
IP720H4 20130528130526  in refrigerator FOUND LAST  IP720H4 20130528131526  in refrigerator
IP720H4 20130528131526  in refrigerator NOT FOUND

I tried stack in order to start searching from the end of the file, but after some pop() stack gets empty. 我尝试了堆栈以便从文件末尾开始搜索,但是在某些pop()堆栈变空之后。

while(!lifo.empty())
{
    String[] next_line = lifo.pop().toString().split(" ");

    //This is the abrcode of the next line
    String next_barcode = next_line[0].toString();

    //barcode is the one i am trying to find (last of the file)
    if (next_barcode.equals(barcode))
    {
        System.out.println(nnext_barcode + " found");
        break;
    }
    else
    {
        //NOT FOUND
    }
}

But as i said this is not the correct approach, cause the stack gets empty. 但是正如我说的那样,这不是正确的方法,这会导致堆栈变空。 I want to search line by line but the STRUCTURE should get empty, in order to continue with other lines (last, second last, etc). 我想逐行搜索,但STRUCTURE应该为空,以便继续其他行(最后,第二倒数等)。

What can i do? 我能做什么?

Use a Map<String, String> . 使用Map<String, String> The barcode is the key in the map: 条形码是地图中的键:

 String lastLine = map.get( barcode );
 if( null != lastLine ) {
     ... found previous line; do something with it ...
 }

 map.put( barcode, line );

Use a normal loop to read the file line by line. 使用普通循环逐行读取文件。

You could store the data in an array and work with two nested loops. 您可以将数据存储在数组中,并使用两个嵌套循环。 This is not the most efficient way but probably the simplest. 这不是最有效的方法,但可能是最简单的方法。 Example: 例:

String[] data;
// read input into data array

for (int i = data.length - 1; i >= 0; --i) { // begins with the last line and continues until first line
  String currentBarcode = getBarcode(data[i]);

  for (int j = i - 1; i >= 0; --j) { // begins with the line before current line and tests every line on same barcode
    if (getBarcode(data[j] == currentBarcode) {
      // print output
      break; // end search when barcode found
    }
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM