Regarding arrayList - java
I have used scanner instead of string tokenizer ,, below is the piece of code...
Scanner scanner = new Scanner("Home,1;Cell,2;Work,3");
scanner.useDelimiter(";");
while (scanner.hasNext()) {
// System.out.println(scanner.next());
String phoneDtls = scanner.next();
// System.out.println(phoneDtls);
ArrayList<String> phoneTypeList = new ArrayList<String>();
if(phoneDtls.indexOf(',')!=-1) {
String value = phoneDtls.substring(0, phoneDtls.indexOf(','));
phoneTypeList.add(value);
}
Iterator itr=phoneTypeList.iterator();
while(itr.hasNext())
System.out.println(itr.next());
}
The ouput I get upon executing this...
Home
Cell
Work
As it is seen from the above code is that in the array list phoneTypeList we are finally storing the values..but the logic of finding out the value on the basisi of ',' is not that much great..that is ..
if(phoneDtls.indexOf(',')!=-1) {
String value = phoneDtls.substring(0, phoneDtls.indexOf(','));
phoneTypeList.add(value);
}
could you please advise me with some other alternative ..!! to achieve the same thing...!!thanks a lot in advance..!!
Well, since you asked if there is another way to do it then here is an alternative: You can split the string directly and do it with less code with the foreach statement:
String input = "Home,1;Cell,2;Work,3";
String[] splitInput = input.split(";");
for (String s : splitInput ) {
System.out.println(s.split(",")[0]);
}
No need to use the ArrayList<T> since you can iterate over an array as well.
could you try to split based on ',' STIRNG_VALUE.split(','); will return u an array with strings separated with , may be this helps
If i understand correctly. The problem statement is you want to maintain a list of Phone-Type-List. Like this: ["Home", "Cell", "Work"].
I suggest you keep this in a property file / config file / database which ever makes sense and load it to memory on start of you app.
If the input cannot be changed then as for the algorithm i couldn't think of a better one. Looks good.
You could use split function of string if that makes sense.
First use split on ";"
Then a split on ","
declare the arraylist outside the while loop.
try this, i have made some change for better performance too. hope you can compare and understand the change.
ArrayList<String> phoneTypeList = new ArrayList<String>();
Scanner scanner = new Scanner("Home,1;Cell,2;Work,3");
scanner.useDelimiter(";");
String phoneDtls = null;
String value = null;
while (scanner.hasNext()) {
phoneDtls = scanner.next();
if (phoneDtls.indexOf(',') != -1) {
value = phoneDtls.split(",")[0];
phoneTypeList.add(value);
}
}
Iterator itr = phoneTypeList.iterator();
while (itr.hasNext())
System.out.println(itr.next());
I have executed n got the result, check screenshot.
Related
accessing array outside the parent for loop in JAVA
i have this code snippet in my java application. i need to access the rule_body_arr_l2 outside the parent for loop. i tried to initialize the array outside the for loop but in the last line when i want to display its value, it says the array might not have been initialized yet. String rule_body="person(?x),patientid(?y),haspid(?x,?y)"; System.out.println(rule_body); String rule_body_arr[]=rule_body.split("\\),"); String rule_body_arr_l2[]; for(int x=0;x<rule_body_arr.length;x++) { System.out.println(rule_body_arr[x]); rule_body_arr_l2=rule_body_arr[x].split("\\("); System.out.println("LEVEL TWO SPLIT"); for(int y=0;y<rule_body_arr_l2.length;y++) { System.out.println(rule_body_arr_l2[y]); } } for(int x=0;x<6;x++) { System.out.println(rule_body_arr_l2[x]); } Guidance is required in the matter
In Java, you must specify the array size. You haven't created an array. What you have done is, you have only created an array reference. By default, in Java all references are set to null when initializing. You must instantiate an array by giving an exact size for it. For example, int[] numberArray = new int[5];
If I understand your question, rather than using a split to parse the String you could use a regular expression with a Pattern to parse your String with something like String rule_body = "person(?x),patientid(?y),haspid(?x,?y)"; Pattern p = Pattern.compile("person\\((.+)\\),patientid\\((.+)\\),haspid\\((.+)\\)"); Matcher m = p.matcher(rule_body); if (m.matches()) { System.out.printf("person = %s%n", m.group(1)); System.out.printf("patientid = %s%n", m.group(2)); System.out.printf("haspid = %s%n", m.group(3)); } Which outputs person = ?x patientid = ?y haspid = ?x,?y
If so then initialize rule_body_arr_l2 like String[] rule_body_arr_l2 = new String[YOUR_POSSIBLE_LENGTH]; If you are not sure the length of String in prior declaration then better using ArrayList<String> like ArrayList<String> rule_body_arr_l2= new ArrayList<String>();
try splitting at ), u wont get the comma problem
How to only get the lines you want from an arraylist depending on how they start, IN JAVA
I have a very long string containing GPS data but this is not important. What I need to do is separate the string which is in an arraylist (one big string) into multiple pieces. The tricky part is that the string is made up of multiple 'gps sentances' and I only require two types of these sentences. The types I need start with $GPSGSV and $GPSGGA. Basically I need to dump ONLY THESE sentences into another arraylist while leaving all the rest behind. The new arraylist must be in line-by-line form so that each sentence is followed by a new line. Each sentence also ends in one white space which could be helpful when splitting up. The arraylist data is shown below. - This is printed from the arraylist. [$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A, $GPRMC,151018.000,A,5225.9627,N,00401.1624,W,0.11,104.71,210214,,*14, $GPGGA,151019.000,5225.9627,N,00401.1624,W,1,09,1.0,38.9,M,51.1,M,,0000*72, $GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A, $GPGSV,3,1,12,26,80,302,44,09,55,063,40,05,53,191,39,08,51,059,37*79, $GPGSV,3,2,12,28,43,112,34,15,40,284,42,21,18,305,33,07,18,057,27*7E, $GPGSV,3,3,12,10,05,153,,24,05,234,38,18,05,318,22,19,05,035,*79, $GPRMC,151019.000,A,5225.9627,N,00401.1624,W,0.10,105.97,210214,,*1D, $GPGGA,151020.000,5225.9627,N,00401.1624,W,1,09,1.0,38.9,M,51.1,M,,0000*78, $GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A, $GPRMC,151020.000,A,5225.9627,N,00401.1624,W,0.12,105.18,210214,,*12, $GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A, $GPRMC,151021.000,A,5225.9626,N,00401.1624,W,0.11,99.26,210214,,*28, $GPGGA,151022.000,5225.9626,N,00401.1623,W,1,09,1.0,38.9,M,51.1,M,,0000*7C, $GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A, $GPRMC,151022.000,A,5225.9626,N,00401.1623,W,0.11,109.69,210214,,*1F, The data continues up to 2000 sentences. Any help would be great. Thanks EDITS ------ Looking back at what I have.. It may be best if I just read in the lines (as the file is formatted to be one sentence per line) which start with either the GSV or the GGA tag. In the buffered reader section of the method, how could I go about doing that? Here is some of my code .... try { File gpsioFile = new File(gpsFile); FileReader file = new FileReader(gpsFile); BufferedReader buffer = new BufferedReader(file); StringBuffer stringbuff = new StringBuffer(); String ans; while ((ans = buffer.readLine()) != null) { gps.add(ans); stringbuff.append(ans); stringbuff.append("\n"); } } catch (Exception e) { e.printStackTrace(); } From this could I get an Arraylist with just the GGA and GSV sentences/lines but in the same order that they were from the file? Thanks
OK, I'd first start by splitting your string into individual lines with spilt(): String[] split = "$GPGSA,A,3,28,09,26,15,08,05,21,24,07,,,,1.6,1.0,1.3*3A,".split(","); you can also use "\n" as a split delimiter instead of ",". This will give you an array over which you can iterate. List<String> filtered = new ArrayList<String>() for (String item, split) { if (item.startsWith("$GPGSA")) { filtered.add(item); } } filtered would be a new Array with the items you want to keep. This approach works with JDK 6+. In JDK 8, this kind of problem can be solved more elegantly with the stream API.
My understanding is that you've got an ArrayList with a single String element. That String is a comma separated list of values. So step one is to extract the string and split it into it's constituent parts. Once you've done that you can process the each item in turn. private static List<List<String>> splitData(final ArrayList<String> data) { final List<List<String>> filteredData = new ArrayList<List<String>>(); String fullText = data.get(0); String[] splitData = fullText.split(","); List<String> currentList = null; for (int i = 0;i < splitData.length; i++) { final String next = splitData[i]; if (startTags.contains(next)) { if (interestingStartTags.contains(next)) { currentList = new ArrayList<String>(); filteredData.add(currentList); } else { currentList = null; } } if (currentList != null) { currentList.add(next); } } return filteredData; } The two static Set<String> provide the set of all 'gps sentence' start tags and also the set of ones you're interested in. The split data method uses startTags to determine if it has reached the start of a new sentence. If the new tag is also interesting, then a new list is created and added to the List<List<String>>. It is this list of lists that is returned. If you don't know all of the strings you want to use as 'startTag' then you could next.startsWith("$GP") or similar. Reading the file Looking at the updated question of how to read the file you could remove the StringBuffer and instead simply add each line you read to an ArrayList. The code below will step over any lines that do not start with the two tags you are interested in. The order of the lines within lineList will match the order they are found in the file. FileReader file = new FileReader(gpsFile); BufferedReader buffer = new BufferedReader(file); String ans; ArrayList<String> lineList = new ArrayList<String>(); while ((ans = buffer.readLine()) != null) { if (ans.startsWith("$GPSGSV")||ans.startsWith("$GPSGGA")) { lineList.add(ans); } }
Two dimensional string array in java
I am new to java please help me with this issue. I have a string lets say adc|def|efg||hij|lmn|opq now i split this string and store it in an array using String output[] = stringname.split("||"); now i again need to split that based on '|' and i need something like arr[1][]=adc,arr[2][]=def and so on so that i can access each and every element. something like a 2 dimensional string array. I heard this could be done using Arraylist, but i am not able to figure it out. Please help.
Here is your solution except names[0][0]="adc", names[0][1]="def" and so on: String str = "adc|def|efg||hij|lmn|opq"; String[] obj = str.split("\\|\\|"); int i=0; String[][] names = new String[obj.length][]; for(String temp:obj){ names[i++]=temp.split("\\|"); } List<String[]> yourList = Arrays.asList(names);// yourList will be 2D arraylist. System.out.println(yourList.get(0)[0]); // This will print adc. System.out.println(yourList.get(0)[1]); // This will print def. System.out.println(yourList.get(0)[2]); // This will print efg. // Similarly you can fetch other elements by yourList.get(1)[index]
What you can do is: String str[]="adc|def|efg||hij|lmn|opq".split("||"); String str2[]=str[0].split("|"); str2 will be containing abc, def , efg // arrays have toList() method like: Arrays.asList(any_array);
Can hardly understand your problem... I guess you may want to use a 2-dimenison ArrayList : ArrayList<ArrayList<String>> String input = "adc|def|efg||hij|lmn|opq"; ArrayList<ArrayList<String>> res = new ArrayList<ArrayList<String>>(); for(String strs:input.split("||")){ ArrayList<String> strList = new ArrayList<String>(); for(String str:strs.split("|")) strList.add(str); res.add(strList); }
how to retrieve a line with spaces with comma as separator?
I have this record in my game.txt file menard,menard mabunga,0 francis,francis mabunga,0 angelica,francis mabunga,1 I access the file and store it in an array list using this code; Scanner s = new Scanner(getResources().openRawResource(R.raw.game)); ArrayList<String> list = new ArrayList<String>(); while (s.hasNext()){ list.add(s.next()); } s.close(); And use this function to load a random line; public static String randomLine(ArrayList list) { return (String) list.get(new Random().nextInt(list.size())); } When I try to print the result of the randomLine function using System.out.println(randomLine(list)); the output is mabunga,0 only. Now, how can I retrieve a line with spaces with comma as separator?
You are reading words instead of lines. Use nextLine() instead of next(). So, this should be your code: Scanner s = new Scanner(getResources().openRawResource(R.raw.game)); ArrayList<String> list = new ArrayList<String>(); while (s.hasNext()){ list.add(s.nextLine()); // Change here!! } s.close(); I prefer BufferedReader over Scanner if the goal is to read lines.
You should instantiate Random ony once, and store a reference to it. Otherwise, nextInt() will always return the same value.
Use a String Tokenizer (or a Stream Tokenizer if you want to separate them while reading the file). Set the separator to ",". Then you should be fine. In the randomLine function use the following piece of code, instead of yours: public static String randomLine(ArrayList list) { return (String) list.get((int)(Math.Random()*list.size())); }
Extracting token from a string
I've a some strings like that "paddington road" and I need to extract the word "road" from this string. How can I do that? The problem is that I need to process a list of streets and extract some words like "road" "park" "street" "boulevard" and many others. What could be the best way to do that? The complexity is O(n*m) and if you consider that I process more than 5000 streets, the performance should be very important. I'm extracting the values from a Postgres db and putting into a List but I'm not sure it's the best way, may be a hash table is faster to query? I tried something like this: // Parse selectedList Iterator<String> it = streets.iterator(); Iterator<String> it_exception = exception.iterator(); int counter = streets.size(); while(it.hasNext()) { while ( it_exception.hasNext() ) { // remove substring it_exception.next() from it.next() } } What do you think?
You can try Set: Set<String> exceptions = new HashSet<String>(...); for (String street : streets) { String[] words = street.split(" "); StringBuilder res = new StringBuilder(); for (String word : words) { if (!exceptions.contains(word)) { res.append(word).append(" "); } } System.out.println(res); } I think complexity will be O(n), where n is a number of all words in streets.
You need to get a new iterator for your list of keywords at each iteration of the outer loop. The easiest way is to use the foreach syntax: for (String streetName : streets) { for (String keyword : keywords) { // find if the string contains the keyword, and perhaps break if found to avoid searching for the other keywords } } Don't preoptimize. 5000 is nothing for a computer, and street names are short strings. And if you place the most frequent keywords (street, rather than boulevard) at the beginning of the keyword list, you'll have less iterations.
List streets = new ArrayList<String>(); streets.add("paddington road"); streets.add("paddington park"); for (Object object : streets) { String cmpstring = object.toString(); String[] abc = cmpstring.split(" "); String secondwrd = abc[1]; System.out.println("secondwrd"+secondwrd); } you can keep secondwrd in a list or string buffer etc....