convert a String to a multi-dimensional array - java

Context: I have converted an array into a string, then into bytes so that it can be stored as a blob in a database. I then want to retrieve the array. I retrieve the blob and retrieve the string from the bytes. I then want to retrieve the array from the string.
Now I had been looking at various options to convert my string back into an array. I had looked at using string.split() with certain regex to get my array back, however, this gets a bit complicated with it being multidimensional. However is there a simple way to convert a string back to array where the string still contains its original "array syntax"?
e.g.
Array array = {1, 2, 3}
String string = array.toString()
[insert string back to array]
Cheers!
p.s. can an array be stored in a database (google app engine) without the need for this inefficient convoluted method?

You can store the List as a EmbeddedProperty.
For example, here you have the general utility class I use for those kind of needs...
import java.util.ArrayList;
import java.util.List;
import com.google.appengine.api.datastore.EmbeddedEntity;
/**
* Utility class for storing Lists of simple objects
* #author toni.navarro
*
*
*
*/
#SuppressWarnings("unchecked")
public class ListTransformer<T> {
public List<T> toList(List<EmbeddedEntity> embeddedList) {
List<T> list = new ArrayList<T>();
if (embeddedList!=null) {
for (EmbeddedEntity embeddedEntity: embeddedList) {
list.add((T) embeddedEntity.getProperty("value"));
}
}
return list;
}
public List<EmbeddedEntity> toEmbeddedList(List<T> list) {
List<EmbeddedEntity> embeddedList = new ArrayList<EmbeddedEntity>();
if (list!=null) {
for (T item: list) {
EmbeddedEntity embeddedItem = new EmbeddedEntity();
embeddedItem.setUnindexedProperty("value", item);
embeddedList.add(embeddedItem);
}
}
return embeddedList;
}
}
... and then use it with something like:
embeddedEntity.setUnindexedProperty("possibleQuestions", new ListTransformer<Long>().toEmbeddedList(turn.getPossibleQuestions()));
... and:
turn.setPossibleQuestions(new ListTransformer<Long>().toList((List<EmbeddedEntity>)embeddedEntity.getProperty("possibleQuestions")));

Why would you store it as blob? Convert the array to a string: "1,2,3". Then, when loading, do something like: loadedString.split(",") and iterate over the array (the result of the split() method is String[]) and add it to the Array data structure that you are using.

Use the split method which parses a string accorign tot a given delimiter and returns an array out of it.
Take a look at this exmaple:
//split string example
String assetClasses = "Gold:Stocks:Fixed Income:Commodity:Interest Rates";
String[] splits = asseltClasses.split(":");
System.out.println("splits.size: " + splits.length);
for(String asset: assetClasses){
System.out.println(asset);
}
OutPut
splits.size: 5
Gold
Stocks
Fixed Income
Commodity
Interest Rates

Convert string into two dimensional string array in Java gives the answer.
In particular:
If you know how many rows and columns there will be, you can pre-allocate a String[][] and use a Scanner as follows:
Scanner sc = new Scanner(data).useDelimiter("[,|]");
final int M = 3;
final int N = 2;
String[][] matrix = new String[M][N];
for (int r = 0; r < M; r++) {
for (int c = 0; c < N; c++) {
matrix[r][c] = sc.next();
}
}
System.out.println(Arrays.deepToString(matrix));
// prints "[[1, apple], [2, ball], [3, cat]]"

public static void main(String[] args) {
String s = "my name is abc";
StringTokenizer strTokenizer = new StringTokenizer(s);
List<String> arrayList = new ArrayList<String>();
while (strTokenizer.hasMoreTokens()) {
arrayList.add(strTokenizer.nextToken());
}
List<List<String>> lst = new ArrayList<List<String>>();
lst.add(arrayList);
for (int i = 0; i < lst.size(); i++) {
for (int j = 0; j < 1; j++) {
System.out.println("Element " + lst.get(j));
}
}
}

Related

How to remove certain elements from my array in my Java code

I am working on the following coding prompt for my class:
Your task is to write a method with the following signature:
public static String[] removeFromArray(String[] arr, String toRemove)
The method should return a string array that has the same contents as arr, except without any
occurrences of the toRemove string. For example, if your method is called by the code below
String[] test = {“this”, “is”, “the”, “example”, “of”, “the”, “call”};
String[] result = removeFromArray(test, “the”);
System.out.println(Arrays.toString(result));
it should generate the following output:
[this, is, example, of, call]
Note: Your method will be passed values for arr and toRemove by the testing program – you should not
read these values in from the user inside your method. Also, you must write this method with the
signature requested above in order to receive credit. You do not need to write the code that calls the
method – only the method itself.
Hint: Because you must specify the length of an array when you create it, you will likely need to make
two loops through the input array: one to count the number of occurrences of the toRemove string so
that you can create the new array with the proper size and a second to copy all of the other strings to the new array.
I have everything working in my code but the last part where I have to print out the new array does not work, I know I have make it smaller so it will print out properly, but I can't get that part to work. I know I have to get rid of the null, but I don't know how. Also my code has to work for any array not just the test case I have. Some help or advice would really be nice. Thank you very much!!! :)
Here is my code:
public static void main(String[] args) {
String[] test = {"this", "is", "the", "example", "of", "the", "call"};
String[] remove = removeFromArray(test, "the");
System.out.println(Arrays.toString(remove));
}
public static String[] removeFromArray(String[] arr, String toRemove) {
int count = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i].equals(toRemove)) {
count++;
}
}
String[] result = new String[arr.length - count];
//for (int i = 0; i < arr.length; i++) {
// if(!arr[i].equals(toRemove)){
// result[].equals(arr[i]);
//}
//}
return result;
}
you approach looks ok, it looks like the commented code yor are trying to assign the new array with the wrong emthod
you should use result[i] = arr[i] ; instead of result[].equals(arr[i]);
do at the end:
String[] result = new String[arr.length - count];
int k = 0;
for (int i = 0; i < arr.length; i++) {
if(!toRemove.equals(arr[i])){
result[k] = arr[i];
k++;
}
}
return result;
Your last part should be assigning the value to the array one by one.
int j = 0;
for (int i = 0; i < arr.length; i++) {
if(!toRemove.equals(arr[i])){
result[j++] = arr[i];
}
}
It's asking you to return a new String array which excludes the given word. Loop through the array and add word which does not equal to the given word.
public static String[] removeFromArray(String[] arr, String toRemove){
ArrayList<String> words = new ArrayList<>();
for(String s : arr)
if(!s.equals(toRemove))
words.add(s);
return words.toArray(new String[0]);
}
Since array size cannot be changed after being created, use an ArrayList to store the words, then return as an array.
I know you're new to programming itself, so the solutions given are perfectly fine.
However, using Java, you'd usually use the libraries; in this case, the Collections library. If you're using Java 8, this is how you would do it:
public static String[] removeFromArray(String[] arr, String toRemove) {
// create a List and fill it with your items
ArrayList<String> list = new ArrayList();
Collections.addAll(list, arr);
// remove the items that are equal to the one to be removed
list.removeIf(s -> toRemove.equals(s));
// transfer back to array
return list.toArray(new String[list.size()]);
}
Then, there are Java 8 Streams, which would make this
public static String[] removeFromArray(String[] arr, String toRemove) {
return Arrays.stream(arr) // create stream from array
.filter(s -> !toRemove.equals(s)) // filter out items
.toArray(String[]::new); // create array from stream
}

Converting List<ArrayList> to String[]

I have a
List<ArrayList> arg = new ArrayList<ArrayList>();
with
[[logo], [cd_branche], [lib_branche]],
(other arguments not relevant)
[[1111,22222,3333]],[[2222,324,432]]...
and I want to cast it to a String[] so I did this
Object[] obj = arg.toArray();
String[] headers =new String[obj.length];
for(int i=0;i<headers.length;i++) {
headers[i]= (String) obj[i];
}
but I'm getting
java.util.ArrayList cannot be cast to java.lang.String
The output I'm looking for is
headers[0]=logo
headers[1]=cd_branche
headers[2]=lib_branche
Using Java 6
It sounds like you want it to be an array of strings (i.e. "[["logo", "cd_branche", "lib_cranche"],[..],[..],[1111,22222,3333],[2222,324,432]").
In that case simply do:
Object[] obj = arg.toArray();
String[] headers =new String[obj.length];
for(int i=0;i<headers.length;i++) {
headers[i]= Arrays.toString(obj);
}
And each one of your ArrayList objects inside obj will be returned in string array format.
UPDATE: Since you want it as a flat array, you'll need to (a) compute the size of the array needed and (b) run through your object with two loops and make a deep search as such:
int size = 0;
for (int i = 0; i < arg.size(); size += arg.get(i++).size());
String[] headers =new String[size];
for(int count = 0, i=0;i<arg.size();i++) {
for (int j=0; j< arg.get(i).size(); j++) {
headers[count++]= arg.get(i).get(j).toString();
}
}
String headers = "";
for (String header:arg)
{headers += header;}

JTextField to int[] array?

I'm working on my graphic user interface for a application I'm creating. Basically there is this JTextField that the user has to input integers. For example
25, 50, 80, 90
Now, I have this other class that needs to get those values and put them in an int Array.
I've tried the following.
guiV = dropTheseText.getText().split(",");
And in the other class file I retieve the String, but I have no idea how to get the value for each one.
In the end I'm just trying to get something like
int[] vD = {textfieldvaluessplitbycommahere};
Still fairly new to Java but this has me crazy.
private JTextField txtValues = new JTextField("25, 50, 80, 90");
// Strip the whitespaces using a regex since they will throw errors
// when converting to integers
String values = txtValues.getText().replaceAll("\\s","");
// Get the inserted values of the text field and use the comma as a separator.
// The values will be returned as a string array
private String[] strValues = values.split(",");
// Initialize int array
private int[] intValues = new int[strValues.length()];
// Convert each string value to an integer value and put it into the integer array
for(int i = 0; i < strValues.length(); i++) {
try {
intValues[i] = Integer.parseInt(strValues[i]);
} catch (NumberFormatException nfe) {
// The string does not contain a parsable integer.
}
}
As you are fairly new to Java, rather than giving you the code snippet, I will just give you some indications:
Use the String class: it has a method for splitting a String into an array of Strings.
Then use the Integer class: it has a method to convert a String to an int.
You cant do it directly, you may need to add a method to convert your string array to int array. Something like this:
public int[] convertStringToIntArray(String strArray[]) {
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
return intArray;
}
Pass your guiV to this method and get back the int array
a simple solution is a function hat does the conversion:
public static int[] convertTextFieldCommaSeparatedIntegerStringToIntArray(String fieldText) {
String[] tmp = fieldText.split(",");
int[] result = new int[tmp.length];
for(int i = 0; i < tmp.length; i++) {
result[i] = Integer.parseInt(tmp[i].trim());
}
return result;
}
The essential methods are:
split for splitting the original input at the comma.
parseInt for converting a String -> int. The valueOf function of Integer is an option but then you have to convert String -> Integer -> int.
Note:
You should use trim to eliminate white-spaces. Furthermore, you should catch the NumberFormatException thrown by parseInt. As an unchecked exception you do not need to catch it, but it is always wise to check user input and sanitize it if necessary.
Try this code:
public int[] getAsIntArray(String str)
{
String[] values = str.getText().split(",");
int[] intValues = new int[values.length];
for(int index = 0; index < values.length; index++)
{
intValues[index] = Integer.parseInt(values[index]);
}
return intValues;
}

Convert string array to int array (generics?)

I have a string that I want to split with a certain delimiter
private int [] mMaxValues;
public void setMaximum(String maximum) {
mMaxValues = splitByDelimiter(maximum, ":");
}
But the splitByDelimiter method return a string array into an int array
public String[] splitByDelimiter(String list,String delimiter) {
String[] items = list.split("\\" + delimiter);
for (String s : items) {
s.trim();
}
return items;
}
What is the best way to fix this problem? I'm guessing that iterating the string array and casting them to integers isn't the best solution.
I could also create a new splitByDelimiter that returns an int array but I'm guessing there is a better solution than that..
Is this a situation where you could use generics (I don't have a lot of experience with generics)?
Thx :)
You need to convert string array to int array explicitly. Use:
public void setMaximum(String maximum) {
Strin[] array = splitByDelimiter(maximum, ":");
int i = 0;
mMaxValues = new int[array.length];
for (String value : array) {
mMaxValues[i] = Integer.parseInt(value);
i++;
}
}
Also you need to handle few cases which may cause NullPointerException :
maximum is null
array is null
NumberFormatException may be raised while parsing Integer.parseInt(value), handle it.
Loop over the string array and store them in an int array.
String input = ...;
String[] parts = input.split(':');
int[] result = new int[parts.length];
for (int n = 0; n < parts.length; ++n)
{
result[n] = Integer.parseInt(parts[n]);
}
return result

Using String.split() to access numeric values

i tried myself lot but can't get a solution so i'm asking help.
i have an string String input="---4--5-67--8-9---";
now i need to convert in into an string array which will look like:
String [][]output={{4},{5},{67},{8},{9}};
i tried with split() and
java.util.Arrays.toString("---4--5-67--8-9---".split("-+")
but can't find the desired answer. so what to do?
actually i need the value 4,5,67,8,9.but i'm not sure how to find them. i will treat the values as integer for further processing
String[] numbers = "---4--5-67--8-9---".split("-+");
String[][] result = new String[numbers.length][1];
for (int i = 0; i < numbers.length; i++) {
result[i][0] = numbers[i];
}
Update: to get rid of the initial empty value, you can get a substring of the input, like:
int startIdx = 0;
char[] chars = input.toCharArray();
for (int i = 0; i < chars.length; i ++) {
if (Character.isDigit(chars[i])) {
startIdx = i;
break;
}
}
input = input.substring(startIdx);
(or you can check them for not being empty (String.isEmpty()) when processing them later.)
First, here is the answer to your question. This code will generate a two-dimensional array where each element is an array consisting of a single numeric string.
final String input = "---4--5-67--8-9---";
// desired output: {{4},{5},{67},{8},{9}}
// First step: convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create the two-dimensional array with the correct size
final String[][] arrayOfArrays = new String[arrayOfStrings.length][];
// Loop over single-dimension array to initialize the two-dimensional one
for(int i = 0; i < arrayOfStrings.length; i++){
final String item = arrayOfStrings[i];
arrayOfArrays[i] = new String[] { item };
}
System.out.println(Arrays.deepToString(arrayOfArrays));
// Output: [[4], [5], [67], [8], [9]]
However, I think what you really need is an array of Integers or ints, so here is a revised solution:
final String input = "---4--5-67--8-9---";
// Convert all non-digits to whitespace
// so we can cut it off using trim()
// then split based on white space
final String[] arrayOfStrings =
input.replaceAll("\\D+", " ").trim().split(" ");
// Now create an array of Integers and assign the values from the string
final Integer[] arrayOfIntegers = new Integer[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfIntegers[i] = Integer.valueOf(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfIntegers));
// Output: [4, 5, 67, 8, 9]
// Or alternatively an array of ints
final int[] arrayOfInts = new int[arrayOfStrings.length];
for(int i = 0; i < arrayOfStrings.length; i++){
arrayOfInts[i] = Integer.parseInt(arrayOfStrings[i]);
}
System.out.println(Arrays.toString(arrayOfInts));
// Output: [4, 5, 67, 8, 9]
Whether you use the Integer or the int version really depends on whether you want to just do some math (int) or need an object reference (Integer).
String[] result = "---4--5-67--8-9---".split("-+");
int i;
for (i = 0; i < result.length; i++) {
if (result[i].length() > 0) {
System.out.println(result[i]);
}
}
gives me output:
4
5
67
8
9
public class split{
public static void main(String[] argv){
String str="---4--5-67--8-9---";
String[] str_a=str.split("-+");
}
}
This seems to working for me.
Using a regex pattern seems more natural in this case:
public class split {
public static int[] main(String input) {
ArrayList<String> list = new ArrayList() ;
Pattern pattern = Pattern.compile("[0-9]") ;
Matcher matcher = pattern.matcher(input) ;
String match = null ;
while( ( match = matcher.find() ) === true ) {
list.add(match) ;
}
String[] array = list.toArray( new String[ ( list.size() ) ]() ) ;
return array ;
}
}
String input="---4--5-67--8-9---";
Scanner scanner = new Scanner(input).useDelimiter("-+");
List<Integer> numbers = new ArrayList<Integer>();
while(scanner.hasNextInt()) {
numbers.add(scanner.nextInt());
}
Integer[] arrayOfNums = numbers.toArray(new Integer[]{});
System.out.println(Arrays.toString(arrayOfNums));
I thought the following is quite simple, although it uses List and Integer arrays, Its not that an overhead for small strings:
For simplicity, I am returning a single dimension array, but can be easily modified to return an array you want. But from your question, it seems that you just want a list of integers.
import java.util.*;
public class Test {
public static void main(String[] args) throws Throwable {
String input = "---4--5-67--8-9---";
System.out.println(split(input).length); // 5
}
public static Integer[] split(String input) {
String[] output = input.split("\\-+");
List<Integer> intList = new ArrayList<Integer>(output.length);
// iterate to remove empty elements
for(String o : output) {
if(o.length() > 0) {
intList.add(Integer.valueOf(o));
}
}
// convert to array (or could return the list itself
Integer[] ret = new Integer[intList.size()];
return intList.toArray(ret);
}
}
I might be late to the party but I figured I'd give the guava take on this.
String in = "---4--5-67--8-9---";
List<String> list = Lists.newArrayList(Splitter.on("-").omitEmptyStrings().trimResults().split(in));
System.out.println(list);
// prints [4, 5, 67, 8, 9]

Categories