type casting a String to Object[][] - java

I would like to convert below String to simple two dimensional array (Object[][]).
String personArray ="{{Melroy,25,India},{Jack,26,USA}}"; // nothing but a simple string with appearance of a 2D array
Can this be done in the first place?
If so what is the simplest way?
Any help any inputs will be greatly appreciated.

Starting from beginning, identify format of your data structure,
seems like your inner array have format {String, Number, String}, to find it, we will create simple regular expression \\{([A-Za-z]+),([0-9]+),([A-Za-z]+)\\}
to make it work properly, you might need to add few modifications, but bellow code will work for your small case
String personArray ="{{Melroy,25,India},{Jack,26,USA}}";
Pattern pattern = Pattern.compile("\\{([A-Za-z]+),([0-9]+),([A-Za-z]+)\\}");
Matcher matcher = pattern.matcher(personArray);
List<Object[]> list = new ArrayList<>();
//using list as we don't know number of final elements,
int start = 0;
while(
matcher.find(start)){
list.add(new Object[]{matcher.group(1),matcher.group(2),matcher.group(3)});
start = matcher.end();
}
//convert to array, to have required format
Object[][] array = list.toArray(new Object[0][]);
//test result
for (Object[] arr : array)
System.out.println(Arrays.toString(arr));

Related

Java help regarding of arrays and printing out the individual lengths in the arrays

Currently, I have trouble attempting to print out the individual lengths efficiently.
String[] array = {"test", "testing", "tests"};
int arraylength = array[0].length();
System.out.println(arraylength);
Now, this does work in printing out the length however, it is inefficient and doesn't work if theoretically I don't know the length of the array.
Thanks for your input and I would appreciate if the code insisted contains "System.out.println" included so I don't have trouble figuring out which to print out.
Use this:
String[] array = {"test", "testing", "tests"};
for(String str : array) {
System.out.println(str.length());
}
If you are using Java 8 then it's a one liner :)
Arrays.asList(array).forEach(element -> System.out.println(element.length()));
What you are doing is, converting your array to a list and then running a for loop over it. Then for every element, you are printing out the length of the element.
EDIT
From one of the comment, this is even a better version of my code.
Arrays.stream(array).map(String::length).forEach(System.out::println);
Here first you convert your array to a list and then map each element to the function length of string class, then you run a foreach over it which prints out the mapped values.
String[] array = {"test", "testing", "tests"};
The length for array is:
int arraylength = array.length;
To have retrieve length for string:
for(String string: array) {
System.out.println(string.length());
}

Splitting a String array and storing in a list

There is a string[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"} which needs to be split on the basis of , and -. The values aa,dd,aa should be stored in one list whereas bb,hh in another list. I have written this code snippet:
String[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"};
for(int i=0;i<arr.length;i++){
newArr = arr[i].split(",");
for(int j=0;j<newArr.length;j++){
resultArr = newArr[j].split("-");
appList.add(resultArr[0]);
prodList.add(resultArr[1]);
rolList.add(rresultArr[2]ol);
}
Above approach could be better if we do arr[i].split in another way so that we can run only one loop but I could not achieve that so far.
I wanted to know is there any best way to achieve the requirement.
You don't need to split it using , ,since it's not part of the String but part of the String array declaration syntax,just split it with a -
String[] arr = {"aa-bb-cc","dd-bb-ee","aa-hh-gg"};
for(int i=0;i<arr.length;i++){
newArr = arr[i].split("-");
appList.add(newArr[0]);
prodList.add(newArr[1]);
rolList.add(newArr[2]);
}

Separating an argument string into double java

So I'm trying to develop a method using String.split and Double.parseDouble and i really need some help! I am relatively new to programming. I'm using Java.
Anyhow, this method interprets a sequence of numbers separated by commas to produce an array of Strings, then it parses each of the strings to get a double, then stores them in sequence.
So far I've managed to separate the String arguments into individual lines:
public class Sequence
{
...
public Sequence(String a)
{
for (String returnvalue: s.split(",")){
System.out.println(returnvalue);
}
}
...
}
At this point i am just so lost! However i do have each of the Strings seperated into individual lines. From here i just have to use the parser to convert the Strings into Doubles and store them in sequence.
Any help would be greatly appreciated! Thank you!
Also, does anyone know where i could learn more about Java programming? I am stuck for resources.
Well, the split() method returns an array. You're looping through it fine, so all you need to do is parse each string into a double for each loop iteration to get an array of doubles:
String[] tokens = s.split(",");
double[] result = new double[tokens.length];
int i = 0; // This is used for putting each double in the array
for(String token:tokens) {
result[i++] = Double.parseDouble(token);
}
Create List like:
String[] array = a.split(",");
List<Double> doubleList = new ArrayList<>(array.length);
for (String token : array) {
doubleList.add(Double.valueOf(token));
}

Concatenating String Arrays in For Loops with String conditions

I currently am running a for loop which reads a List object and then splits them into arrays. Here is the sample code:
List<String> lines = Arrays.asList("foo,foo,foo","bar,baz,foo","foo,baz,foo", "baz,baz,baz", "zab,baz,zab");
for (String line : lines){
String[] array = line.split(",");
String[] arraySplit2 = array[0].split(",");
System.out.print(Arrays.toString(arraySplit2));
}
The output is:
[foo][bar][foo][baz][zab]
I wish to concatenate the array strings into a single one under the loop so that it displays:
[foo, bar, foo, baz, zab]
I'm having a bit of trouble because the conditions of the loop prevent me from doing the increase int i trick and using System.arraycopy(). I'm open to ideas such as changing the structure of the loop itself.
You seem to be trying to create an array out of first items from each line.
First, So you need to create the result array first with the size of number of lines:
String[] result = new String[lines.size()];
int index = 0;
You do not need the second split, in the for loop populate the result array:
result[index++] = array[0]
After the loop print your result array.
Not 100% sure on what you want, but I guess something like this:
List<String> outList = new ArrayList<String>();
for (String line : lines) {
String[] array = line.split(",");
outList.add(array[0]);
}
String[] outStr = outList.toArray(new String[0]);
System.out.println(Arrays.toString(outStr));

String Array to 2D String array

I have a String Array, map[] which looks like...
"####"
"#GB#"
"#BB#"
"####"
So map[1] = "#GB#"
How do I turn this into a 2D array so that newMap[1][1] would give me "G"?
Thanks a lot.
If you really need it, you can use String.toCharArray on each element array to convert them into an array.
String[] origArr = new String[10];
char[][] charArr = new char[10][];
for(int i = 0; i< origArr.length;i++)
charArr[i] = origArr[i].toCharArray();
If you want to break it up into String[] instead, you could use (thanks Pshemo)
String[] abc = "abc".split("(?!^)"); //-> ["a", "b", "c"]
This won't be dynamic. It will take O(n) + m to get to a character of a string. A much faster and dynamic approach would be a Hashmap where the key is the String and the value is a char array. Kind of unnecessarily complex but you get the seeking and individual letter charAts without having to go through the cumbersome process of resizing a primitive array.

Categories