-1

I have data in my text file in the following format

apple fruit
carrot vegetable
potato vegetable 

I want to read this line by line and split at the first space and store it in a set or map or any similar collections of java. (key and value pairs)

example :-
"apple fruit" should be stored in a map where the key = apple and value = fruit.

Federico Tomassetti
  • 1,732
  • 1
  • 17
  • 24
  • Hello and welcome to SO. It looks like you haven't invested much time in research on this topic, otherwise you would have found a bunch of examples. If you still think you need help from the community, please present code of your own solution that we could discuss and suggest improvements to. It is unlikely that someone would be happy to do the complete task for you. – Eduard Malakhov Feb 15 '17 at 20:18

3 Answers3

2

The Scanner class is probably what you're after.

As an example:

 Scanner sc = new Scanner(new File("your_input.txt"));
 while (sc.hasNextLine()) {
     String line = sc.nextLine();
     // do whatever you need with current line
 }
 sc.close(); 
Ben Siver
  • 2,230
  • 21
  • 41
0

You can do something like this:

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String currentLine;
while ((currentLine = br.readLine()) != null) {
  String[] strArgs = currentLine.split(" "); 
  //Use HashMap to enter key Value pair.
  //You may to use fruit vegetable as key rather than other way around
}
0

Since java 8 you can just do

Set<String[]> collect = Files.lines(Paths.get("/Users/me/file.txt"))
            .map(line -> line.split(" ", 2))
            .collect(Collectors.toSet());

if you want a map, you can just replace the Collectors.toSet by Collectors.toMap()

Map<String, String> result = Files.lines(Paths.get("/Users/me/file.txt"))
            .map(line -> line.split(" ", 2))
            .map(Arrays::asList)
            .collect(Collectors.toMap(list -> list.get(0), list -> list.get(1)));
jelle
  • 750
  • 7
  • 22