0

I'm currently writing an app that takes the data from the file. I need to sort the data in different ways. The problem is that the file is in format:

NAME1(tab)A(tab)B
NAME2(tab)C(tab)D

I want to split data into two ArrayLists, one will gather NAME1, NAME2 etc, so the first element of line, the second list will gather the rest.

Here's my code:

Scanner scan = new Scanner(new File(fname));

while(scan.hasNext()){

}
scan.close();

System.out.println("Lang: ");
for(String item : lang)
    System.out.print(item + " ");

} catch (FileNotFoundException e) {
    e.printStackTrace();
}

I tried to play with scanner methods, but there are no results and I have no idea what to do.

Ryan
  • 1,972
  • 2
  • 23
  • 36
Mrfk
  • 15
  • 4

3 Answers3

1

Here is the recipe

fileInputStreamObj = StreamTests.class.getResourceAsStream(your_file_path);
bufferedReaderObj = new BufferedReader(new InputStreamReader(fileInputStreamObj));

bufferedReaderObj
  .lines()
  .map(s -> {
    String[] splitStrings = s.split("\t", -1);
    return Arrays.asList(splitStrings);
  }).forEach(System.out::println);

Some thing that I tested .

Aravind.HU
  • 9,194
  • 5
  • 38
  • 50
1

Here is my attempt:

List<String> list1 = new ArrayList<>();
List<String> list2 = Files.lines(Paths.get(fname)).flatMap(s -> {
    String[] line = s.split("\\t");
    if (line.length > 0) {
        list1.add(line[0]);
    }
    return Arrays.stream(line).skip(1);
}).collect(Collectors.toList());
David Pérez Cabrera
  • 4,960
  • 2
  • 23
  • 37
0

I would just use Scanner.nextLine(), then String.split("\t") and then append the line's parts to the respective lists.

Stefan Reich
  • 1,000
  • 9
  • 12