How to read a list of ArrayLists from file?
up vote
0
down vote
favorite
I'm trying to read a file which contains adjacency list of a graph. The file looks like this:
1 2 3 5
2 4
3 1 5
4
5 2 4
Each line is a linked list with some length different than other lines. So far I tried this:
private static List<ArrayList<String>> adj;
ArrayList<String> rows = new ArrayList<String>();
int i = 0;
try
Scanner input = new Scanner(new BufferedReader(new FileReader(fileName)));
//BufferedReader input = new BufferedReader(new FileReader(fileName));
String line;
while (input.hasNextLine())
i++;
String cols = input.nextLine().trim().split(" ");
for (String c : cols)
rows.add(c);
adj.add(rows);
//print the matrix
for (List<String> list : adj)
for (String str : list)
System.out.print(str + " ");
System.out.println();
catch (IOException e)
System.out.println("Error reading input file!");
but it doesn't work, because it shows an error (NullPointerException) when I try to print the whole matrix. How can I read this file properly?
java list arraylist
|
show 3 more comments
up vote
0
down vote
favorite
I'm trying to read a file which contains adjacency list of a graph. The file looks like this:
1 2 3 5
2 4
3 1 5
4
5 2 4
Each line is a linked list with some length different than other lines. So far I tried this:
private static List<ArrayList<String>> adj;
ArrayList<String> rows = new ArrayList<String>();
int i = 0;
try
Scanner input = new Scanner(new BufferedReader(new FileReader(fileName)));
//BufferedReader input = new BufferedReader(new FileReader(fileName));
String line;
while (input.hasNextLine())
i++;
String cols = input.nextLine().trim().split(" ");
for (String c : cols)
rows.add(c);
adj.add(rows);
//print the matrix
for (List<String> list : adj)
for (String str : list)
System.out.print(str + " ");
System.out.println();
catch (IOException e)
System.out.println("Error reading input file!");
but it doesn't work, because it shows an error (NullPointerException) when I try to print the whole matrix. How can I read this file properly?
java list arraylist
You need to addrows = new ArrayList<String>();afteradj.add(rows);
– Ivan
Nov 9 at 19:55
@Ivan I tried that. But there was no change. Still can't print the whole matrix.
– Hadi GhahremanNezhad
Nov 9 at 20:06
Then please add code that you use to print. And also exception stack trace.
– Ivan
Nov 9 at 20:09
1
The problem is that you need to initialize "adj".
– paulsm4
Nov 9 at 20:15
2
As @paulsm4 said replaceprivate static List<ArrayList<String>> adj;withprivate static List<ArrayList<String>> adj = new ArrayList<>();
– Ivan
Nov 9 at 20:16
|
show 3 more comments
up vote
0
down vote
favorite
up vote
0
down vote
favorite
I'm trying to read a file which contains adjacency list of a graph. The file looks like this:
1 2 3 5
2 4
3 1 5
4
5 2 4
Each line is a linked list with some length different than other lines. So far I tried this:
private static List<ArrayList<String>> adj;
ArrayList<String> rows = new ArrayList<String>();
int i = 0;
try
Scanner input = new Scanner(new BufferedReader(new FileReader(fileName)));
//BufferedReader input = new BufferedReader(new FileReader(fileName));
String line;
while (input.hasNextLine())
i++;
String cols = input.nextLine().trim().split(" ");
for (String c : cols)
rows.add(c);
adj.add(rows);
//print the matrix
for (List<String> list : adj)
for (String str : list)
System.out.print(str + " ");
System.out.println();
catch (IOException e)
System.out.println("Error reading input file!");
but it doesn't work, because it shows an error (NullPointerException) when I try to print the whole matrix. How can I read this file properly?
java list arraylist
I'm trying to read a file which contains adjacency list of a graph. The file looks like this:
1 2 3 5
2 4
3 1 5
4
5 2 4
Each line is a linked list with some length different than other lines. So far I tried this:
private static List<ArrayList<String>> adj;
ArrayList<String> rows = new ArrayList<String>();
int i = 0;
try
Scanner input = new Scanner(new BufferedReader(new FileReader(fileName)));
//BufferedReader input = new BufferedReader(new FileReader(fileName));
String line;
while (input.hasNextLine())
i++;
String cols = input.nextLine().trim().split(" ");
for (String c : cols)
rows.add(c);
adj.add(rows);
//print the matrix
for (List<String> list : adj)
for (String str : list)
System.out.print(str + " ");
System.out.println();
catch (IOException e)
System.out.println("Error reading input file!");
but it doesn't work, because it shows an error (NullPointerException) when I try to print the whole matrix. How can I read this file properly?
java list arraylist
java list arraylist
edited Nov 9 at 20:32
Stephen P
10.6k13350
10.6k13350
asked Nov 9 at 19:48
Hadi GhahremanNezhad
1451314
1451314
You need to addrows = new ArrayList<String>();afteradj.add(rows);
– Ivan
Nov 9 at 19:55
@Ivan I tried that. But there was no change. Still can't print the whole matrix.
– Hadi GhahremanNezhad
Nov 9 at 20:06
Then please add code that you use to print. And also exception stack trace.
– Ivan
Nov 9 at 20:09
1
The problem is that you need to initialize "adj".
– paulsm4
Nov 9 at 20:15
2
As @paulsm4 said replaceprivate static List<ArrayList<String>> adj;withprivate static List<ArrayList<String>> adj = new ArrayList<>();
– Ivan
Nov 9 at 20:16
|
show 3 more comments
You need to addrows = new ArrayList<String>();afteradj.add(rows);
– Ivan
Nov 9 at 19:55
@Ivan I tried that. But there was no change. Still can't print the whole matrix.
– Hadi GhahremanNezhad
Nov 9 at 20:06
Then please add code that you use to print. And also exception stack trace.
– Ivan
Nov 9 at 20:09
1
The problem is that you need to initialize "adj".
– paulsm4
Nov 9 at 20:15
2
As @paulsm4 said replaceprivate static List<ArrayList<String>> adj;withprivate static List<ArrayList<String>> adj = new ArrayList<>();
– Ivan
Nov 9 at 20:16
You need to add
rows = new ArrayList<String>(); after adj.add(rows);– Ivan
Nov 9 at 19:55
You need to add
rows = new ArrayList<String>(); after adj.add(rows);– Ivan
Nov 9 at 19:55
@Ivan I tried that. But there was no change. Still can't print the whole matrix.
– Hadi GhahremanNezhad
Nov 9 at 20:06
@Ivan I tried that. But there was no change. Still can't print the whole matrix.
– Hadi GhahremanNezhad
Nov 9 at 20:06
Then please add code that you use to print. And also exception stack trace.
– Ivan
Nov 9 at 20:09
Then please add code that you use to print. And also exception stack trace.
– Ivan
Nov 9 at 20:09
1
1
The problem is that you need to initialize "adj".
– paulsm4
Nov 9 at 20:15
The problem is that you need to initialize "adj".
– paulsm4
Nov 9 at 20:15
2
2
As @paulsm4 said replace
private static List<ArrayList<String>> adj; with private static List<ArrayList<String>> adj = new ArrayList<>();– Ivan
Nov 9 at 20:16
As @paulsm4 said replace
private static List<ArrayList<String>> adj; with private static List<ArrayList<String>> adj = new ArrayList<>();– Ivan
Nov 9 at 20:16
|
show 3 more comments
3 Answers
3
active
oldest
votes
up vote
1
down vote
accepted
Edited
I reproduced your code, made the initializtion of the list, added try/catch and added the printing code and this is working fine:
List<ArrayList<String>> adj = new ArrayList<>();
int i = 0;
Scanner input = null;
try
input = new Scanner(new BufferedReader(new FileReader(fileName)));
catch (FileNotFoundException e)
e.printStackTrace();
String line;
while (input.hasNextLine())
ArrayList<String> rows = new ArrayList<String>();
i++;
String cols = input.nextLine().trim().split(" ");
for (String c : cols)
rows.add(c);
adj.add(rows);
for (ArrayList<String> list : adj)
for (String s : list)
System.out.print(s + " ");
System.out.println();
add a comment |
up vote
1
down vote
You really should use methods from the "new" Java NIO (introduced in Java 7) together with streams (introduced in Java 8) for this:
public void readLinesExample(String fileName) throws IOException
List<List<String>> adj = Files.readAllLines(Paths.get(fileName)).stream()
.map(row -> row.split(" "))
.map(Arrays::asList)
.collect(toList());
System.out.println(adj.stream().flatMap(Collection::stream).collect(joining(" ")));
These few lines does all the job, wrapped in a main() method.
It is pretty straightforward:
- First read all the lines, which returns a list. Create a stream from the rows of the file. This call throws the
IOExceptionso you might want to wrap this in an example if you truly want to handle the exception by printing to standard out. - The second line splits each row to an array.
- The third line,
map(Arrays::asList)creates aListfrom each array. - Finally the lists are collected to a list of lists.
The print part is equally simple. It streams over the list of lists, and uses flat map to "flatten" the sub lists to one stream. It then joins the elements to a string, separated by " ", and prints it.
This is much less error prone than your original code, you can hardly do wrong. Of course, it differs in some minor ways, like toList() not guaranteeing that you get an ArrayList, but that is rarely important.
add a comment |
up vote
1
down vote
In another approach using Java 8, you can simplify your code and write something like this to read the file containing your adjacency list of a graph or any similar data.
public static void printGraph() throws Exception
List<String> numberList = Files.readAllLines(Paths.get("graph.txt")); // reads all lines in one shot into a List<String>
List<List<Integer>> listOfIntegerList = new ArrayList<List<Integer>>();
for (String s : numberList) // for each line containing numbers, stores them into a List<Integer>
listOfIntegerList.add(Arrays.stream(s.split("\s+")).map(Integer::parseInt).collect(Collectors.toList()));
System.out.println(listOfIntegerList);
This gives following output as per the data present in your file,
[[1, 2, 3, 5], [2, 4], [3, 1, 5], [4], [5, 2, 4]]
add a comment |
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
1
down vote
accepted
Edited
I reproduced your code, made the initializtion of the list, added try/catch and added the printing code and this is working fine:
List<ArrayList<String>> adj = new ArrayList<>();
int i = 0;
Scanner input = null;
try
input = new Scanner(new BufferedReader(new FileReader(fileName)));
catch (FileNotFoundException e)
e.printStackTrace();
String line;
while (input.hasNextLine())
ArrayList<String> rows = new ArrayList<String>();
i++;
String cols = input.nextLine().trim().split(" ");
for (String c : cols)
rows.add(c);
adj.add(rows);
for (ArrayList<String> list : adj)
for (String s : list)
System.out.print(s + " ");
System.out.println();
add a comment |
up vote
1
down vote
accepted
Edited
I reproduced your code, made the initializtion of the list, added try/catch and added the printing code and this is working fine:
List<ArrayList<String>> adj = new ArrayList<>();
int i = 0;
Scanner input = null;
try
input = new Scanner(new BufferedReader(new FileReader(fileName)));
catch (FileNotFoundException e)
e.printStackTrace();
String line;
while (input.hasNextLine())
ArrayList<String> rows = new ArrayList<String>();
i++;
String cols = input.nextLine().trim().split(" ");
for (String c : cols)
rows.add(c);
adj.add(rows);
for (ArrayList<String> list : adj)
for (String s : list)
System.out.print(s + " ");
System.out.println();
add a comment |
up vote
1
down vote
accepted
up vote
1
down vote
accepted
Edited
I reproduced your code, made the initializtion of the list, added try/catch and added the printing code and this is working fine:
List<ArrayList<String>> adj = new ArrayList<>();
int i = 0;
Scanner input = null;
try
input = new Scanner(new BufferedReader(new FileReader(fileName)));
catch (FileNotFoundException e)
e.printStackTrace();
String line;
while (input.hasNextLine())
ArrayList<String> rows = new ArrayList<String>();
i++;
String cols = input.nextLine().trim().split(" ");
for (String c : cols)
rows.add(c);
adj.add(rows);
for (ArrayList<String> list : adj)
for (String s : list)
System.out.print(s + " ");
System.out.println();
Edited
I reproduced your code, made the initializtion of the list, added try/catch and added the printing code and this is working fine:
List<ArrayList<String>> adj = new ArrayList<>();
int i = 0;
Scanner input = null;
try
input = new Scanner(new BufferedReader(new FileReader(fileName)));
catch (FileNotFoundException e)
e.printStackTrace();
String line;
while (input.hasNextLine())
ArrayList<String> rows = new ArrayList<String>();
i++;
String cols = input.nextLine().trim().split(" ");
for (String c : cols)
rows.add(c);
adj.add(rows);
for (ArrayList<String> list : adj)
for (String s : list)
System.out.print(s + " ");
System.out.println();
edited Nov 9 at 20:18
answered Nov 9 at 20:10
forpas
3,6171214
3,6171214
add a comment |
add a comment |
up vote
1
down vote
You really should use methods from the "new" Java NIO (introduced in Java 7) together with streams (introduced in Java 8) for this:
public void readLinesExample(String fileName) throws IOException
List<List<String>> adj = Files.readAllLines(Paths.get(fileName)).stream()
.map(row -> row.split(" "))
.map(Arrays::asList)
.collect(toList());
System.out.println(adj.stream().flatMap(Collection::stream).collect(joining(" ")));
These few lines does all the job, wrapped in a main() method.
It is pretty straightforward:
- First read all the lines, which returns a list. Create a stream from the rows of the file. This call throws the
IOExceptionso you might want to wrap this in an example if you truly want to handle the exception by printing to standard out. - The second line splits each row to an array.
- The third line,
map(Arrays::asList)creates aListfrom each array. - Finally the lists are collected to a list of lists.
The print part is equally simple. It streams over the list of lists, and uses flat map to "flatten" the sub lists to one stream. It then joins the elements to a string, separated by " ", and prints it.
This is much less error prone than your original code, you can hardly do wrong. Of course, it differs in some minor ways, like toList() not guaranteeing that you get an ArrayList, but that is rarely important.
add a comment |
up vote
1
down vote
You really should use methods from the "new" Java NIO (introduced in Java 7) together with streams (introduced in Java 8) for this:
public void readLinesExample(String fileName) throws IOException
List<List<String>> adj = Files.readAllLines(Paths.get(fileName)).stream()
.map(row -> row.split(" "))
.map(Arrays::asList)
.collect(toList());
System.out.println(adj.stream().flatMap(Collection::stream).collect(joining(" ")));
These few lines does all the job, wrapped in a main() method.
It is pretty straightforward:
- First read all the lines, which returns a list. Create a stream from the rows of the file. This call throws the
IOExceptionso you might want to wrap this in an example if you truly want to handle the exception by printing to standard out. - The second line splits each row to an array.
- The third line,
map(Arrays::asList)creates aListfrom each array. - Finally the lists are collected to a list of lists.
The print part is equally simple. It streams over the list of lists, and uses flat map to "flatten" the sub lists to one stream. It then joins the elements to a string, separated by " ", and prints it.
This is much less error prone than your original code, you can hardly do wrong. Of course, it differs in some minor ways, like toList() not guaranteeing that you get an ArrayList, but that is rarely important.
add a comment |
up vote
1
down vote
up vote
1
down vote
You really should use methods from the "new" Java NIO (introduced in Java 7) together with streams (introduced in Java 8) for this:
public void readLinesExample(String fileName) throws IOException
List<List<String>> adj = Files.readAllLines(Paths.get(fileName)).stream()
.map(row -> row.split(" "))
.map(Arrays::asList)
.collect(toList());
System.out.println(adj.stream().flatMap(Collection::stream).collect(joining(" ")));
These few lines does all the job, wrapped in a main() method.
It is pretty straightforward:
- First read all the lines, which returns a list. Create a stream from the rows of the file. This call throws the
IOExceptionso you might want to wrap this in an example if you truly want to handle the exception by printing to standard out. - The second line splits each row to an array.
- The third line,
map(Arrays::asList)creates aListfrom each array. - Finally the lists are collected to a list of lists.
The print part is equally simple. It streams over the list of lists, and uses flat map to "flatten" the sub lists to one stream. It then joins the elements to a string, separated by " ", and prints it.
This is much less error prone than your original code, you can hardly do wrong. Of course, it differs in some minor ways, like toList() not guaranteeing that you get an ArrayList, but that is rarely important.
You really should use methods from the "new" Java NIO (introduced in Java 7) together with streams (introduced in Java 8) for this:
public void readLinesExample(String fileName) throws IOException
List<List<String>> adj = Files.readAllLines(Paths.get(fileName)).stream()
.map(row -> row.split(" "))
.map(Arrays::asList)
.collect(toList());
System.out.println(adj.stream().flatMap(Collection::stream).collect(joining(" ")));
These few lines does all the job, wrapped in a main() method.
It is pretty straightforward:
- First read all the lines, which returns a list. Create a stream from the rows of the file. This call throws the
IOExceptionso you might want to wrap this in an example if you truly want to handle the exception by printing to standard out. - The second line splits each row to an array.
- The third line,
map(Arrays::asList)creates aListfrom each array. - Finally the lists are collected to a list of lists.
The print part is equally simple. It streams over the list of lists, and uses flat map to "flatten" the sub lists to one stream. It then joins the elements to a string, separated by " ", and prints it.
This is much less error prone than your original code, you can hardly do wrong. Of course, it differs in some minor ways, like toList() not guaranteeing that you get an ArrayList, but that is rarely important.
answered Nov 9 at 20:47
Magnilex
6,95363459
6,95363459
add a comment |
add a comment |
up vote
1
down vote
In another approach using Java 8, you can simplify your code and write something like this to read the file containing your adjacency list of a graph or any similar data.
public static void printGraph() throws Exception
List<String> numberList = Files.readAllLines(Paths.get("graph.txt")); // reads all lines in one shot into a List<String>
List<List<Integer>> listOfIntegerList = new ArrayList<List<Integer>>();
for (String s : numberList) // for each line containing numbers, stores them into a List<Integer>
listOfIntegerList.add(Arrays.stream(s.split("\s+")).map(Integer::parseInt).collect(Collectors.toList()));
System.out.println(listOfIntegerList);
This gives following output as per the data present in your file,
[[1, 2, 3, 5], [2, 4], [3, 1, 5], [4], [5, 2, 4]]
add a comment |
up vote
1
down vote
In another approach using Java 8, you can simplify your code and write something like this to read the file containing your adjacency list of a graph or any similar data.
public static void printGraph() throws Exception
List<String> numberList = Files.readAllLines(Paths.get("graph.txt")); // reads all lines in one shot into a List<String>
List<List<Integer>> listOfIntegerList = new ArrayList<List<Integer>>();
for (String s : numberList) // for each line containing numbers, stores them into a List<Integer>
listOfIntegerList.add(Arrays.stream(s.split("\s+")).map(Integer::parseInt).collect(Collectors.toList()));
System.out.println(listOfIntegerList);
This gives following output as per the data present in your file,
[[1, 2, 3, 5], [2, 4], [3, 1, 5], [4], [5, 2, 4]]
add a comment |
up vote
1
down vote
up vote
1
down vote
In another approach using Java 8, you can simplify your code and write something like this to read the file containing your adjacency list of a graph or any similar data.
public static void printGraph() throws Exception
List<String> numberList = Files.readAllLines(Paths.get("graph.txt")); // reads all lines in one shot into a List<String>
List<List<Integer>> listOfIntegerList = new ArrayList<List<Integer>>();
for (String s : numberList) // for each line containing numbers, stores them into a List<Integer>
listOfIntegerList.add(Arrays.stream(s.split("\s+")).map(Integer::parseInt).collect(Collectors.toList()));
System.out.println(listOfIntegerList);
This gives following output as per the data present in your file,
[[1, 2, 3, 5], [2, 4], [3, 1, 5], [4], [5, 2, 4]]
In another approach using Java 8, you can simplify your code and write something like this to read the file containing your adjacency list of a graph or any similar data.
public static void printGraph() throws Exception
List<String> numberList = Files.readAllLines(Paths.get("graph.txt")); // reads all lines in one shot into a List<String>
List<List<Integer>> listOfIntegerList = new ArrayList<List<Integer>>();
for (String s : numberList) // for each line containing numbers, stores them into a List<Integer>
listOfIntegerList.add(Arrays.stream(s.split("\s+")).map(Integer::parseInt).collect(Collectors.toList()));
System.out.println(listOfIntegerList);
This gives following output as per the data present in your file,
[[1, 2, 3, 5], [2, 4], [3, 1, 5], [4], [5, 2, 4]]
answered Nov 9 at 20:52
Pushpesh Kumar Rajwanshi
2,6461821
2,6461821
add a comment |
add a comment |
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53232390%2fhow-to-read-a-list-of-arraylists-from-file%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
You need to add
rows = new ArrayList<String>();afteradj.add(rows);– Ivan
Nov 9 at 19:55
@Ivan I tried that. But there was no change. Still can't print the whole matrix.
– Hadi GhahremanNezhad
Nov 9 at 20:06
Then please add code that you use to print. And also exception stack trace.
– Ivan
Nov 9 at 20:09
1
The problem is that you need to initialize "adj".
– paulsm4
Nov 9 at 20:15
2
As @paulsm4 said replace
private static List<ArrayList<String>> adj;withprivate static List<ArrayList<String>> adj = new ArrayList<>();– Ivan
Nov 9 at 20:16