The program reads text from a specific file.

List<String> lines = Files.readAllLines("path", StandartCharsets.UTF8); for(String lines:source){ 

Next comes the regular expression that finds certain lines from the file. How to make the numbering of each line when reading and at the end to output the regular lines found in the cannibal along with the line number?

  • 2
    Read not in the list, but in the array. Then, when searching elements, the index in the array (+1) will be the line number. - PinkTux
  • @PinkTux than the index in the array is kosher than the index in the list? - Russtam
  • @Russtam, strange question. Obviously, it depends on the context of the application. There are lots of options, somewhere is better, somewhere, and somewhere completely different ... In any case, an array index is a more natural entity than an index for a list. - PinkTux
  • @PinkTux well, we know the context, and even if you do not pay attention to the fact that modifying the example so that there is an array of strings, it will complicate it, the fact that there is an array of strings does not help in solving the problem. Because the fact that you are iterating a list or an array does not make a difference, you will not have an index. It is necessary to change foreach to a normal cycle or start a counter. Therefore, your proposal to read into an array, instead of a list, does not make sense. - Russtam
  • @Russtam, yes to health. You can do as you want, I allow. - PinkTux

2 answers 2

 for(int i=0; i<lines.size(); i++){ // i = номер строк lines.get(i) } 

    list.index0f (String s) The string you have, get an index type int https://docs.oracle.com/javase/7/docs/api/java/util/List.html#indexOf(java.lang.Object)

    • With a large number of elements will work slowly + if there are identical rows, there will always be an index of the first row. - Russtam