Reputation: 319
I have the following text file :
1 dog
2 bark
3 broccoli
4 vegetable
5 orange
6 fruit
7 shark
8 fish
9 cat
10 meow
11 cricket
12 chirp
I want to make a hash map with a key for every even number and a value for every odd number in the text file. This textfile will have more lines added over time so I do not want to hardcode it.
I read the textile lines through a List and into an ArrayList of strings.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Scanner;
public class brain {
public List<String> Payload1() throws IOException {
Scanner sc = new Scanner (new File("src/boot/Payload1.txt"));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
return lines;
}
I then made a for loop that would get every even and odd number in a separate string using a for loop counter.
String first = Hanes.Payload1().get(i);
String second = null;
if(Hanes.Payload1().size() > i + 1) {
second = Hanes.Payload1().get(i+1);
}
System.out.println(first);
System.out.println(second);
}
I'm not really sure how to implement it into a hash map like this:
private HashMap<String,String> predictionFeatureMapping = new LinkedHashMap<String,String>();
public HashMap<String,String> predictionFeatureMapper() throws IOException {
predictionFeatureMapping = new LinkedHashMap<String,String>();
return predictionFeatureMapping;
}
Upvotes: 0
Views: 2244
Reputation: 693
public Map<String, String> Payload1() throws IOException {
Scanner sc = new Scanner (new File("src/boot/Payload1.txt"));
Map<String, String> fileMap = new LinkedHashMap<String, String>();
int counter = 1;
String key = "";
while (sc.hasNextLine()) {
if(counter % 2 != 0) {
key = sc.nextLine();
}else {
fileMap.put(key, sc.nextLine());
}
counter++;
}
sc.close();
return fileMap;
}
You can just store the key value in a String and then use the put() function during the next line when you have the value to associate with it. The modulus just determines whether you are on a key line or value line. If you would still like to return a list of all the lines for some other use, then use the same logic to create your hashmap:
public Map<String, String> getFileMap(List<String> list){
Map<String, String> fileMap = new LinkedHashMap<String, String>();
String key = "";
for(int x = 0; x < list.size(); x++) {
if((x + 1 ) % 2 != 0) {
key = list.get(x);
}else {
fileMap.put(key, list.get(x));
}
}
return fileMap;
}
Upvotes: 0