How to build the given data structure? Any name for it? - java

I have been given an API that saves data in a field in the following order: ["Hello","world","confused"] .
I don't know how to format like this before I pass my data as an input?
The text values are taken from a checkbox.
If I save it in an array I get "[hello,world,confused]" format.

You save the raw values into a single String. YOu have to save it as an array, list or a map. I will not show map usage in this answer. Example:
//Get the Strings
String ex1 = "hello";
String ex2 = "world";
String ex3 = "confused";
//Array
String[] s = new String[3];
s[0] = ex1;
s[1] = ex2;
s[2] = ex3;
//List
List<String> list = new ArrayList<>();
list.add(ex1);
list.add(ex2);
list.add(ex3);
Now, if you send it over the internet and receive the data, send it as raw strings. Then convert it to List for easability. If the amount of Strings vary, this is the easiest way:
StringBuilder sb = new StringBuilder();
sb.append("[\"");
for(int i = 0; i < list.size()/*or .length if it is an array*/; i++){
if(i == list.size() - 1)
sb.append(list.get(i)/*or array[i]*/ + "\"]");
else
sb.append(list.get(i)/*or array[i]*/ + "\",\"");
}
String f = sb.toString();
//Display list: TextView, print to console, whatever you want to do
These are put in a List because it is much easier to loop a list than to manually add every String.
If the amount of Strings are static, you can use String.format:
String f = String.format(Locale.ENGLISH, "[\"%s\",\"%s\",\"%s\"]", ex1, ex2, ex3);
If I somehow misunderstood your question, let me know so I can edit my answer

Related

Get multiple strings from a single JTextField

I have this text field inside a dialog
dialog.setSize(350,350);
dialog.getContentPane().add(BorderLayout.CENTER,
new JTextField(text));
My goal is when user adds multiple strings inside that text field, to extract the text and split it into strings, and then be able to search in a DB for each string like this:
var res = request_handler.search(
"SELECT Name, ingredients FROM " +
"food WHERE FIND_IN_SET('"+containerObj+"',ingredients)");
I'm thinking for something like this:
String foodSearch = ActionField.getText();
int index = 0;
//create a contaner for the strings
ArrayList<String> container = new ArrayList<>();
container.add("");
//loop until end of string
while(index <= foodSearch.length()){
//if we aren't at new string
if(foodSearch.charAt(index) != ','){
//get the char
char temp = foodSearch.charAt(index);
//then append that char to the String in the container
}
else{
container.add("");
}
++index;
}
Basically will use the comma sign as a separation between the strings, looping thru the whole object. But is there a better way of approaching and solving this problem?

JAVA: How to convert String ArrayList to Integer Arraylist?

My question is -
how to convert a String ArrayList to an Integer ArrayList?
I have numbers with ° behind them EX: 352°. If I put those into an Integer ArrayList, it won't recognize the numbers. To solve this, I put them into a String ArrayList and then they are recognized.
I want to convert that String Arraylist back to an Integer Arraylist. So how would I achieve that?
This is my code I have so far. I want to convert ArrayString to an Int Arraylist.
// Read text in txt file.
Scanner ReadFile = new Scanner(new File("F:\\test.txt"));
// Creates an arraylist named ArrayString
ArrayList<String> ArrayString = new ArrayList<String>();
// This will add the text of the txt file to the arraylist.
while (ReadFile.hasNextLine()) {
ArrayString.add(ReadFile.nextLine());
}
ReadFile.close();
// Displays the arraystring.
System.out.println(ArrayString);
Thanks in advance
Diego
PS: Sorry if I am not completely clear, but English isn't my main language. Also I am pretty new to Java.
You can replace any character you want to ignore (in this case °) using String.replaceAll:
"somestring°".replaceAll("°",""); // gives "sometring"
Or you could remove the last character using String.substring:
"somestring°".substring(0, "somestring".length() - 1); // gives "somestring"
One of those should work for your case.
Now all that's left is to parse the input on-the-fly using Integer.parseInt:
ArrayList<Integer> arrayInts = new ArrayList<Integer>();
while (ReadFile.hasNextLine()) {
String input = ReadFile.nextLine();
try {
// try and parse a number from the input. Removes trailing `°`
arrayInts.add(Integer.parseInt(input.replaceAll("°","")));
} catch (NumberFormatException nfe){
System.err.println("'" + input + "' is not a number!");
}
}
You can add your own handling to the case where the input is not an actual number.
For a more lenient parsing process, you might consider using a regular expression.
Note: The following code is using Java 7 features (try-with-resources and diamond operator) to simplify the code while illustrating good coding practices (closing the Scanner). It also uses common naming convention of variables starting with lower-case, but you may of course use any convention you want).
This code is using an inline string instead of a file for two reasons: It shows that data being processed, and it can run as-is for testing.
public static void main(String[] args) {
String testdata = "55°\r\n" +
"bad line with no number\r\n" +
"Two numbers: 123 $78\r\n";
ArrayList<Integer> arrayInt = new ArrayList<>();
try (Scanner readFile = new Scanner(testdata)) {
Pattern digitsPattern = Pattern.compile("(\\d+)");
while (readFile.hasNextLine()) {
Matcher m = digitsPattern.matcher(readFile.nextLine());
while (m.find())
arrayInt.add(Integer.valueOf(m.group(1)));
}
}
System.out.println(arrayInt);
}
This will print:
[55, 123, 78]
You would have to create a new instance of an ArrayList typed with the Integer wrapper class and give it the same size buffer as the String list:
List<Integer> myList = new ArrayList<>(ArrayString.size());
And then iterate through Arraystring assigning the values over from one to the other by using a parsing method in the wrapper class
for (int i = 0; i < ArrayString.size(); i++) {
myList.add(Integer.parseInt(ArrayString.get(i)));
}

Analyse large String using processing

I have a String which I need to split and add to different arrays.
This is my String
{"locations":[{"latitude":"1.3846519","longitude":"103.763276","startTime":"1422720220292","duration":"0","accuracy":"50.981998443604"},{"latitude":"1.3845814","longitude":"103.7634384","startTime":"1422720520181","duration":"0","accuracy":"55.532001495361"},{"latitude":"1.3844195","longitude":"103.763209","startTime":"1422720820265","duration":"0","accuracy":"34.5"},{"latitude":"1.3844051","longitude":"103.7632272","startTime":"1422721120466","duration":"0","accuracy":"36"},
],"success":1}
The output I want is like this in different arrays.
latitudeArray[] = // String array of latitude values
longitudeArray[] = // String array of longitude values
startTimeArray[] = // String array of start time values
durationArray[] = // String array of duration values
accuracyArray[] = // String array of accuracy values
I am using processing IDE to analyse my data and I tried matchAll() and split() functions but couldn't get it work.
Could you please help me in getting my output? Thanks.
Edit: I managed to extract one latitude value but my method seems very inefficient. How can I do this inside a loop?
String[] locationData = loadStrings("sample.txt");
ArrayList<String> latitudeArray = new ArrayList<String>();
ArrayList<String> longitudeArray = new ArrayList<String>();
ArrayList<String> startTimeArray = new ArrayList<String>();
ArrayList<String> durationArray = new ArrayList<String>();
ArrayList<String> accuracyArray = new ArrayList<String>();
String temp;
int index;
index = locationData[0].indexOf("latitude");
println(index);
temp = locationData[0].substring(index+11);
println(temp);
index = temp.indexOf(",");
println(index);
latitudeArray.add(temp.substring(0,(index-1)));
println(latitudeArray.get(0));
Wasn't sure in what format the loadStrings() method returns, so I just used the initial String you provided.
You're heading in the right direction with the string methods. This code tries to benefit from the single input string. If you split on "latitude", then all the elemets in the array, except for the first one, will have the numbers we're interested on in the begining. E.g.: split("latitude\":\"") gives all the latitudes in the begining:
[0] = {"locations":[{"
[1] = 1.3846519","longitude":"103.763276","startTime":"1422720220292","duration":"0","accuracy":"50.981998443604"},{"
[2] = 1.3845814","longitude":"103.7634384","startTime":"1422720520181","duration":"0","accuracy":"55.532001495361"},{"
[3] = 1.3844195","longitude":"103.763209","startTime":"1422720820265","duration":"0","accuracy":"34.5"},{"
[4] = 1.3844051","longitude":"103.7632272","startTime":"1422721120466","duration":"0","accuracy":"36"}, ],"success":1}
To read the actual numbers, we just need to read until the next quote("). Doing indexOf("\"") will give use the position till which we must read to retrieve that number. So, just perform a substring(0,indexOfQuote) on it to get the value. The repeat again, but this time splitting on "longitude" to get them.
Full program:
public static void main(String[] args) {
final String INPUT = "{\"locations\":["
+ "{\"latitude\":\"1.3846519\",\"longitude\":\"103.763276\",\"startTime\":\"1422720220292\",\"duration\":\"0\",\"accuracy\":\"50.981998443604\"},"
+ "{\"latitude\":\"1.3845814\",\"longitude\":\"103.7634384\",\"startTime\":\"1422720520181\",\"duration\":\"0\",\"accuracy\":\"55.532001495361\"},"
+ "{\"latitude\":\"1.3844195\",\"longitude\":\"103.763209\",\"startTime\":\"1422720820265\",\"duration\":\"0\",\"accuracy\":\"34.5\"},"
+ "{\"latitude\":\"1.3844051\",\"longitude\":\"103.7632272\",\"startTime\":\"1422721120466\",\"duration\":\"0\",\"accuracy\":\"36\"},"
+ " ],\"success\":1}";
String latitudeArray[] = splitAndCollect("latitude", INPUT);
String longitudeArray[] = splitAndCollect("longitude", INPUT);
String startTimeArray[] = splitAndCollect("startTime", INPUT);
String durationArray[] = splitAndCollect("duration", INPUT);
String accuracyArray[] = splitAndCollect("accuracy", INPUT);
System.out.println("Done");
}
private static String[] splitAndCollect(String string, String input) {
final String COLON = "\":\"";
String[] split = input.split(string + COLON);
String[] output = new String[split.length - 1];
for (int i = 0; i < output.length; i++)
// Using [i+1] - since split[0] contains "locations".
// Subsequent splits will have the numbers needed.
output[i] = split[i + 1].substring(0, split[i + 1].indexOf("\""));
System.out.println(string + "\n" + Arrays.toString(output));
return output;
}
If you can preprocess the file to csv. file using simple shell script, then do string processing in java, I think you can get better performance. For csv. file processing in Java, refer http://www.mkyong.com/java/how-to-read-and-parse-csv-file-in-java/ (This blog contains simple sample).
If you do some preprocessing step (even in Java) before parsing, you can get all the values to those string arrays simply with one loop. You can use method suggested by Vineet using single loop. So with preprocessing step overall loop count becomes 2.
Thanks,
Mili
It seems that you have data in JSON format. The way you are trying to get data from the is quite difficult (but doable). You can try JSON parser . Its easy to learn and use. You can find one example here.

Can You Put Java Retval Into an Array

I'm scanning through an array of String objects, each string object is going to be broken down into a regex.
When going through a an enhanced for-loop I'm wondering, is it possible to put the retval into an array?
For example if I have String regex = new String[3];
Where regex[0] = "EVEN_BIN_NUM (0|1)*0"
The enhanced for-loop can break my String object up into EVEN_BIN_NUM and (0|1)*0
I want to be able to put EVEN_BIN_NUM in one array, and (0|1)*0 in another array. Here is the code I have that scans through the String array with the string objects
/*
* Run through each String object and appropriately place them in the kind,
* and explicit.
*/
for (int j = 0; j < regex.length; j++)
{
for (String retval: regex[j].split(" ", 2))
{
System.out.println(retval);
}
}
For regex[0].split(" ", 2) I get EVEN_BIN_NUM and (0|1)*0 returned separately.
Alternatively, if you know how to break this up in a better way, let me know:
EVEN_BIN_NUM (0|1)*0
ODD_BIN_NUM (0|1)*1
PET (cat|dog)
The parts in capital letters are to be put in the "kind" array, and the rest is to be put in another array.
So the kind array would have three strings, and the other array would have three strings.
Hopefully this isn't too confusing....
It might be a good idea to use a Map object to store your information, however, if you wanted to return your analysis as an array, you could return an array of arrays and do the following.
String[] regex = {"EVEN_BIN_NUM (0|1)*0", "ODD_BIN_NUM (0|1)*1", "PET (cat|dog)"} ;
String[][] split = new String[regex.length][];
for(int i = 0; i < regex.length; i++) {
split[i] = regex[i].split(" ", 2);
}
You can then access the data as follows
String firstProperty = split[0][0]; //EVEN_BIN_NUM
String firstRegex = split[0][1]; //(0|1)*0
String secondProperty = split[1][0]; //ODD_BIN_NUM
String secondRegex = split[1][1]; //(0|1)*1
etcetera.
Or using a map:
Map<String, Pattern> map = new HashMap<>();
for(int i = 0; i < regex.length; i++) {
String[] splitLine = regex[i].split(" ", 2);
map.put(splitLine[0], Pattern.compile(splitLine[1]));
}
This way your properties would map straight to your Patterns.
For example:
Pattern petPattern = map.get("PET");

String to ArrayList

App reads TextEdit value to String and then converts to ArrayList. But before converting it removes spaces between words in TextEdit. So after converting I get ArrayList size only 1.
So my question is how to get the real size. I am using ArrayList because of its swap() function.
outputStream.setText("");
stream = inputStream.getText().toString().replace(" ", "");
key = Integer.parseInt(inputKey.getText().toString());
List<String> arrayList = Arrays.asList(stream);
int lenght = arrayList.size();
if (key < lenght)
{
outputStream.append(lenght+"\n");
outputStream.append("OK");
}
else {
outputStream.append(lenght+"\n");
outputStream.append("Error");
}
}
stream = inputStream.getText().toString();
key = Integer.parseInt(inputKey.getText().toString());
List<String> arrayList = new ArrayList<String>();
for (String x : stream.split(" ")) arrayList.add(x);
int lenght = arrayList.size();
if (key < lenght)
{
outputStream.append(lenght+"\n");
outputStream.append("OK");
}
else {
outputStream.append(lenght+"\n");
outputStream.append("Error");
}
That is my guess at what you actually wanted to do...
The size and the length are different things.
You try to get the size when you want the length.
Use arrayList[0].length() instead of your arrayList.size().
If you want to parse your String to an Array try:
List<String> arrayList = Arrays.asList(stream.split(","));
(this example expects that your text is a comma separated list)
Arrays.asList() expect an array as paramter not just a String. A String is like an array of String of size 1 thats why your list is always of size 1. If you want to Store the words of your String use :
Arrays.asList(stream.split(" ")); //Don't use replace method anymore

Categories

Resources