Convert string to arraylistof object - java

I have the following String data that contain arraylist of objects data,How can i convert it to arraylist type
String data="[Score{id=1, value='3.5'},
Score{id=2, value='4.5'},
Score{id=3, value='2.0'}]";

I would omit the brackets [] at start by cutting out the first and last character. Then you have to split the String to get all the objects in an array. At the end you have to convert the String objects to the actual Score classes. You can do that by the same principle, using substring and indexOf methods.
In terms of code, this would look something like this:
// the String containing all the objects
String data="[Score{id=1, value='3.5'}, Score{id=2, value='4.5'}, Score{id=3, value='2.0'}]";
// Cutting out the brackets []
data = data.substring(1, data.length - 1);
// Splitting the String to smaller pieces
// like "Score{id=1, value='3.5'}", etc
String[] array = data.split(",");
// Creating the ArrayList, where we will save the scores
List<Score> scores = new ArrayList<Score>();
for(int i=0;i<array.length;i++) {
// Creating the Score instance
Score score = new Score();
// Omitting the brackets {}
int start = array[i].indefOx("{") + 1;
int end = array[i].indefOx("}");
// Cutting out the String inside brackets {}
String temp = array[i].substring(start, end);
// We use the same principles again to get those values inside the brackets {}.
String[] tempArray = temp.split(",");
for(int j=0;j<tempArray.length;j++) {
int start = array[i].indefOx("=") + 1;
temp2 = tempArray[j].substring(start);
if(j == 0) {
score.setId(Integer.valueOf(temp2));
} else {
// To cut out the ''
score.setValue(temp2.substring(1, temp2.length));
}
}
// adding score instance to the list
scores.add(score);
}
I would just point out that you would have to verify I used the right indexes, when I used substring and indexOf. If this String would be without the "Score" substring, you would be able to convert this more easily, because then the String would represent a JSONArray.

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?

What is the most efficient way to add 3 characters at a time to an araylist from a text file?

Say you have a text file with "abcdefghijklmnop" and you have to add 3 characters at a time to an array list of type string. So the first cell of the array list would have "abc", the second would have "def" and so on until all the characters are inputted.
public ArrayList<String> returnArray()throws FileNotFoundException
{
int i = 0
private ArrayList<String> list = new ArrayList<String>();
Scanner scanCharacters = new Scanner(file);
while (scanCharacters.hasNext())
{
list.add(scanCharacters.next().substring(i,i+3);
i+= 3;
}
scanCharacters.close();
return characters;
}
Please use the below code,
ArrayList<String> list = new ArrayList<String>();
int i = 0;
int x = 0;
Scanner scanCharacters = new Scanner(file);
scanCharacters.useDelimiter(System.getProperty("line.separator"));
String finalString = "";
while (scanCharacters.hasNext()) {
String[] tokens = scanCharacters.next().split("\t");
for (String str : tokens) {
finalString = StringUtils.deleteWhitespace(str);
for (i = 0; i < finalString.length(); i = i + 3) {
x = i + 3;
if (x < finalString.length()) {
list.add(finalString.substring(i, i + 3));
} else {
list.add(finalString.substring(i, finalString.length()));
}
}
}
}
System.out.println("list" + list);
Here i have used StringUtils.deleteWhitespace(str) of Apache String Utils to delete the blank space from the file tokens.and the if condition inside for loop to check the substring for three char is available in the string if its not then whatever character are left it will go to the list.My text file contains the below strings
asdfcshgfser ajsnsdxs in first line and in second line
sasdsd fghfdgfd
after executing the program result are as,
list[asd, fcs, hgf, ser, ajs, nsd, xs, sas, dsd, fgh, fdg, fd]
public ArrayList<String> returnArray()throws FileNotFoundException
{
private ArrayList<String> list = new ArrayList<String>();
Scanner scanCharacters = new Scanner(file);
String temp = "";
while (scanCharacters.hasNext())
{
temp+=scanCharacters.next();
}
while(temp.length() > 2){
list.add(temp.substring(0,3));
temp = temp.substring(3);
}
if(temp.length()>0){
list.add(temp);
}
scanCharacters.close();
return list;
}
In this example I read in all of the data from the file, and then parse it in groups of three. Scanner can never backtrack so using next will leave out some of the data the way you're using it. You are going to get groups of words (which are separated by spaces, Java's default delimiter) and then sub-stringing the first 3 letters off.
IE:
ALEXCY WOWZAMAN
Would give you:
ALE and WOW
The way my example works is it gets all of the letters in one string and continuously sub strings off letters of three until there are no more, and finally, it adds the remainders. Like the others have said, it would be good to read up on a different data parser such as BufferedReader. In addition, I suggest you research substrings and Scanner if you want to continue to use your current method.

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");

Returning Words Within a String Array

I created a method to output a String. Using the split method and a for loop, I added each word in my sentence into a String array, replacxing the last two letters of each word with "ed". Now, my return statement should return each of the words. When I used System.out.print, it worked. When I use a return and call it in my main method, I get this output: "[Ljava.lang.String;#1b6235b"
The error seems so simple but I just don't know where I'm going worng. Any help would be appreciated.
Here is my method:
public String[] processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
// System.out.print(words[i]);
}
}
return words;
}
You are printing arrays but arrays don't have a proper implementation of toString() method by default.
What you see is
"[Ljava.lang.String;#1b6235b"
This is [Ljava.lang.String; is the name for String[].class, the java.lang.Class representing the class of array of String followed by its hashCode.
In order to print the array you should use Arrays.toString(..)
System.out.println(Arrays.toString(myArray));
A good idea however, it returns my Strings in an Array format. My aim
is to return them back into sentence format. So for example, if my
input is, "Hey my name is Fred", it would output as, "Hed ed naed ed
Fred". Sorry, I forgot to add that it also seperates it with commas
when using Arrays.toString
Then you should modify your processInfo() returning a String or creating a new method that convert your String[] to a String.
Example :
//you use like this
String [] processInfoArray = processInfo();
System.out.println(myToString(processInfoArray));
// and in another part you code something like this
public static String myToString(String[] array){
if(array == null || array.length == 0)
return "";
StringBuilder sb = new StringBuilder();
for(int i=0;i<array.length-1;i++){
sb.append(array[i]).append(" ");
}
return sb.append(array[array.length -1]).toString();
}
As much as I can get from your question and comment is that your aim is to return them back into sentence format. So for example, if your input is, "Hey my name is Fred", it would output as, "Hed ed naed ed Fred".
In that case you should return a String, and not an array. I have modified your method a bit to do so. Let me know if you wanted something else.
public String processInfo() {
String sentence = this.phrase;
String[] words = sentence.split(" ");
if (!this.phrase.equalsIgnoreCase("Fred")) {
sentence = "";
for (int i = 0; i < words.length; i++) {
words[i] = words[i].substring(0, words[i].length() - 2).concat(
"ed ");
sentence += " " + words[i];
// System.out.print(words[i]);
}
}
return sentence.trim();
}
Your commented out call to System.out.print is printing each element of the array from inside the loop. Your method is returning a String[]. When you try to print an array, you will get the java representation of the array as you are seeing. You either need to change your method to build and return a string with all the array entries concatenated together, or your calling code needs to loop through the returned array and print each entry.

JAVA SCRIPT - ASSIGN DATA VALUES AUTOMATICALLY TO DATA BY COMMAS

i really need help on this
Lets says the input is parameter - 2,2,2,2
How can i assign the value for every parameter
1st parameter is 2 so the value assign will be 0 and 1.
I have an example of code but it is in java and i need to do it in JavaScript
for(int i=0; i<args.length;i++)
{
if(args[i].equals("-i"))
{
String data_str= new String();
//SPECIFY DATA VALUES
if(i+1<args.length)
{
i++;
System.out.println ("Parameter => "+args[i]);
data_str=args[i};
}
//ASSIGN DATA VALUES AUTOMATICALLY TO DATA BY COMMAS
StringTokenizer s = newStringTokenizer (data_str,",")
//COUNT PARAMETER
int p = data_str.replaceAll("[^,]","").length();
p++;//AS AN ARRAY SIZE
data= new int[p];
int k = 0;
while(s.hasMoreTokens())
{
data[k]=Integer.parseInt(s.nextToken());
k++;
}
You can split your input string into array.
"2,2,2,2".split(",")
It will lead you to
["2", "2", "2", "2"]
Then you can do whatever you want with your array of args.
If you need integer value, just parse it
parseInt("2") == 2;

Categories

Resources