Reputation: 618
I have a list stored as a text file, stored as such
Id;name;function
I have a function that takes the text file and reads it in line by line, each line of text is a new item in a List. Achieved by doing the fallowing.
List<String> list
list.add(line);
What I am trying to do is see if some Id such as "0x0640e331" is in the list. And if it is get everything on the line of text that that Id is found. So the fallowing would happen,
0x0604f552;name0;function
0x0640e331;name1;function
0x0342t521;name2;function
Searching for 0x0640e331 would return, 0x0640e331;name1;function.
Any ideas?
Upvotes: 0
Views: 149
Reputation: 2694
use the startsWith
method like this ...
ArrayList<String> queryResult = new ArrayList<String>();
String query = "0x0640e331";
for(String line : list) {
if(line.startsWith(query)) {
queryResult.add(line);
}
}
return queryResult;
This basically checks if a given line in the array-list starts with your query
string. If there is more than one line simply add it in another ArrayList and return that as the result.
Upvotes: 1
Reputation: 4223
If you have a large file so you dont want to read it all and lines in your files are sorted by id, you can implement your own binary search algorithm using RandomAccessFile. To read line in the random position, you first select position, and then read forward and backward until a new line symbol.
Upvotes: 0
Reputation: 2294
You can use Use Map<String,String>
for each element in the list get the string and store it in the map
pseudocode:
for(String item : list) {
String keyName= //use substring to get the id value from the string variable 'item'
map.put(keyName,item);
}
System.out.println(map.get("0x0640e331"));
Upvotes: 0
Reputation: 997
You could use a Map instead of a list. See the sample program given below
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
public class TextProgram {
public static void main(String args[]) {
String lineArray[] = { "0x0604f552;name0;function",
"0x0640e331;name1;function", "0x0342t521;name2;function" };
Map<String, String> map = new HashMap<String, String>();
StringTokenizer tokenizer = null;
for (String string : lineArray) {
tokenizer = new StringTokenizer(string, ";");
map.put(tokenizer.nextToken(), string);
}
System.out.println(map.get("0x0640e331"));
}
}
Upvotes: 0
Reputation: 3407
Use Map<String,List>
Store your id as key in the Map and retrieve the values on the key
Upvotes: 0