convert List<List<Integer>> to 2D char array? - java

I have a List<List<Integer>> arr which is 2D_INTEGER_ARRAY. I need to convert this to 2D char[][] array. I tried with below code but it is giving compilation issue which is obvious but not able to figure out how can I do that?
public static int largestMatrix(List<List<Integer>> arr) {
char[][] matrix = new char[arr.size()][];
for (int i = 0; i < arr.size(); i++) {
List<Integer> row = arr.get(i);
// below line is giving error
matrix[i] = row.toArray(new char[row.size()]);
}
}
Error is:
[Java] The method toArray(T[]) in the type List<Integer> is not applicable for the arguments (char[])

Integer and char are separate types. If you want an integer represented as a digit, you need to convert it (casting will only give you the ASCII representation). Besides, you can't call toArray() with a primitive array. You'll have to iterate and convert manually:
matrix[i] = new char[row.size()];
for (int j = 0; j < row.size(); j++) {
matrix[i][j] = Character.forDigit(row.get(j), 10);
}

Basically you are trying to convert List<Integer> to char[] in this line:
matrix[i] = row.toArray(new char[row.size()]);
You can do so using this:
matrix[i] = row.stream()
.map(j -> Integer.toString(j))
.collect(Collectors.joining())
.toCharArray();

We can do it purely using java-8 streams as follows, I have taken a cue from Kartik's answer on the conversion of Stream of Integer to Stream of char[]:
List<List<Integer>> list = Arrays.asList(Arrays.asList(1,2,3), Arrays.asList(4,5,6), Arrays.asList(7,8,9));
char[][] chars = list.stream().map(l -> l.stream()
.map( i-> Integer.toString(i))
.collect(Collectors.joining())
.toCharArray())
.toArray(char[][]::new);

Related

How to concatenate int and string

I am trying to combine two arrays in Java, one with strings and another with integers:
int [] intArray = {1, 2, 3};
String [] strArray = {"Hello", "World"};
I am trying to get two results like following:
Object [] combinedObjects = {1, 2, 3, "Hello", "World"};
String [] combinedStrings = {"1", "2", "3", "Hello", "World"};
Edit: your question was changed after I posted my answer and it seems a more fitting answer has been posted, Instead of deleting my
post i'm going to leave the last bit here in case you need to do any
conversion from your joined array later in your project.
You also have the option to parse your data (this may be useful to you if you ever want to get the int's back from your array.
int tempInt = Integer.parseInt(tempString);
or alternatively:
String tempString = String.valueOf(tempArray[i]);
A good reference for changing types can be found at javadevnotes
you have two approachs :
1 - using arrayList:
ArrayList a = new ArrayList();
for(int i = 0 ; i < intArray.length ; i++)
a.add(intArray[i]);
for(int i = 0 ; i < strArray.length ; i++)
a.add(strArray[i]);
now you have answer in ArrayList
2 - use String.valueof() method :
String combinedStrings[] = new String[strArray.length+intArray.length];
int index= 0;
for(int i = 0 ; i < strArray.length ; i++)
combinedStrings[index++] = strArray[i];
for(int i = 0 ; i < intArray.length ; i++)
combinedStrings[index++] = String.valueOf(intArray[i]);
now you have answer in combinedStrings array
If you are not stucked to very old java version there is seldom a good reason to use Array. Especially if you want to operate on the array, enlarge or reduce it. The java collection framework is far flexibler. Since java8 the introduction of streams on collections offers a wide range of operations in a very compact coding.
Using streams I would solve your problem as following:
Object [] combinedObjects = Stream.concat(
Arrays.stream( intArray).boxed(),
Arrays.stream( strArray))
.toArray(Object[]::new);
String [] combinedStrings = Stream.concat(
Arrays.stream( intArray).mapToObj( i -> "" + i),
Arrays.stream( strArray))
.toArray(String[]::new);
If your input and your desired output should be a Collection then the code would appear even a little shorter:
Collection<Object> combined = Stream.concat(
intCollection.stream(),
strCollection.stream())
.collect( Collectors.toList() );
You should to convert the Integer values to String to solve your problem, because the Array can have one type of information :
public static void main(String args[]) {
int[] intArray = {1, 2, 3};
String[] strArray = {"Hello", "World"};
String[] combinedStrings = new String[intArray.length + strArray.length];
int i = 0;
while (i < intArray.length) {
//convert int to string with adding an empty string
combinedStrings[i] = intArray[i] + "";
i++;
}
int j = 0;
while (j < strArray.length) {
combinedStrings[i] = strArray[j];
i++;
j++;
}
for (String val : combinedStrings) {
System.out.println(val);
}
}
You can learn more about arrays in Oracle tutorial, part Creating, Initializing, and Accessing an Array

How to convert efficiently binary string to binary byte array in Java?

As an input I have binary string String a = "100110". As output I need to have binary byte array byte[] b = {1,0,0,1,1,0}.
For now I'm using
for (int i=0; i<a.length; i++) {
b[i]= Byte.parseByte(a.substring(i, i+1));
}
But this approach is too slow. Can any one give a better suggestion? Thank you
You can do it without making objects for substrings, like this:
for (int i=0; i<a.length; i++) {
b[i]= a.charAt(i)=='1' ? (byte)1 : (byte)0;
}
The reason your approach is slower is that each call to substring produces a new String object, which becomes eligible for garbage collection as soon as parseByte is done with it.
Assuming the input is valid...
byte[] b = new byte[a.length()];
for (int i = 0; i < b.length; i++) {
b[i] = (byte) (a.charAt(i) - '0');
}
Makes an int[] instead of byte[] but I hope for points for elegance:
int[] a = "100110"
// Turn it into a stream.
.chars()
// Make '0'/'1' into 0/1
.map(c -> c - '0')
// Roll it into an array.
.toArray();

Foreach with multidimensional list

List< List<Integer> > arr = new ArrayList< List<Integer> >();
// filling the array
for(List<Integer> values in arr) {
System.out.println(values[0] + values[1]);
}
Why doesn't it work? It displayes an error that ";" is expected, and that it cannot find the symbol. Simple for doesn't work either:
for(int i = 0; i < arr[]; i++) {
}
That is not the correct syntax for the for each loop in Java. Also, you cannot use the [index] notation for a List. That syntax is reserved for arrays. Here is the proper way to iterate using for each in Java.
for(List<Integer> values : arr) {
System.out.println(values.get(0) + values.get(1));
}
For the second half of your question, you should be iterating from 0 towards the size() of the List.
for(int i = 0; i < arr.size(); i++) {
}

Convert an arraylist to array

I have an Arraylist that I want to convert it into an array. I am using this:
double[] array = new double[list.size()];
double [] array = list.toArray(new double[list.size()]);
but, it does not work. Any idea how I can fix it? Thanks in advance.
It seems it returns object.
For converting a List<Double> to a double[], or anything where you need the primitive type, there's no alternative to doing a traditional for loop (or calling a third-party library method that does a traditional for loop, such as Guava's Doubles.toArray).
double[] array = new double[list.size()];
for (int i = 0; i < list.size(); i++) {
array[i] = list.get(i);
}
Alternately, you could do
Double[] array = list.toArray(new Double[list.size()]);
which would get you the array of boxed Doubles, which might suffice for your purposes anyway.
A List can't contain primitive types. Assuming it contains instances of Double, the only way is to iterate over the list and unbox each element (hoping there's no null in the list):
double[] array = new double[list.size()];
int i = 0;
for (Double d : list) {
array[i] = d;
i++;
}
Please read the java docs:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html
HTH.
Use the Object Double not the primitive double:
ArrayList<Double> list = new ArrayList<Double>();
...add data
Double[] array=list.toArray(new Double[list.size()]);
It should be:
Double[] array = new Double[list.size()];
list.toArray(array); // fill the array
and if you want an array of primitives, iterate over each element in the array:
double[] array = new double[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i).doubleValue();
StringBuffer strBuffer = new StringBuffer();
for(Object o:list){
strBuffer.append(o);
}
double []x = new double[]{strBuffer.toString()};
I consider this should work

char array to int array

I'm trying to convert a string to an array of integers so I could then perform math operations on them. I'm having trouble with the following bit of code:
String raw = "1233983543587325318";
char[] list = new char[raw.length()];
list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++){
num[i] = (int[])list[i];
}
System.out.println(num);
This is giving me an "inconvertible types" error, required: int[] found: char
I have also tried some other ways like Character.getNumericValue and just assigning it directly, without any modification. In those situations, it always outputs the same garbage "[I#41ed8741", no matter what method of conversion I use or (!) what the value of the string actually is. Does it have something to do with unicode conversion?
There are a number of issues with your solution. The first is the loop condition i > raw.length() is wrong - your loops is never executed - thecondition should be i < raw.length()
The second is the cast. You're attempting to cast to an integer array. In fact since the result is a char you don't have to cast to an int - a conversion will be done automatically. But the converted number isn't what you think it is. It's not the integer value you expect it to be but is in fact the ASCII value of the char. So you need to subtract the ASCII value of zero to get the integer value you're expecting.
The third is how you're trying to print the resultant integer array. You need to loop through each element of the array and print it out.
String raw = "1233983543587325318";
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++){
num[i] = raw.charAt(i) - '0';
}
for (int i : num) {
System.out.println(i);
}
Two ways in Java 8:
String raw = "1233983543587325318";
final int[] ints1 = raw.chars()
.map(x -> x - '0')
.toArray();
System.out.println(Arrays.toString(ints1));
final int[] ints2 = Stream.of(raw.split(""))
.mapToInt(Integer::parseInt)
.toArray();
System.out.println(Arrays.toString(ints2));
The second solution is probably quite inefficient as it uses a regular expression and creates string instances for every digit.
Everyone have correctly identified the invalid cast in your code. You do not need that cast at all: Java will convert char to int implicitly:
String raw = "1233983543587325318";
char[] list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
num[i] = Character.digit(list[i], 10);
}
System.out.println(Arrays.toString(num));
You shouldn't be casting each element to an integer array int[] but to an integer int:
for (int i = 0; i > raw.length(); i++)
{
num[i] = (int)list[i];
}
System.out.println(num);
this line:
num[i] = (int[])list[i];
should be:
num[i] = (int)list[i];
You can't cast list[i] to int[], but to int. Each index of the array is just an int, not an array of ints.
So it should be just
num[i] = (int)list[i];
For future references. char to int conversion is not implicitly, even with cast. You have to do something like that:
String raw = "1233983543587325318";
char[] list = raw.toCharArray();
int[] num = new int[list.length];
for (int i = 0; i < list.length; i++){
num[i] = list[i] - '0';
}
System.out.println(Arrays.toString(num));
This class here: http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html should hep you out. It can parse the integers from a string. It would be a bit easier than using arrays.
Everyone is right about the conversion problem. It looks like you actually tried a correct version but the output was garbeled. This is because system.out.println(num) doesn't do what you want it to in this case:) Use system.out.println(java.util.Arrays.toString(num)) instead, and see this thread for more details.
String raw = "1233983543587325318";
char[] c = raw.toCharArray();
int[] a = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
a[i] = (int)c[i] - 48;
}
You can try like this,
String raw = "1233983543587325318";
char[] list = new char[raw.length()];
list = raw.toCharArray();
int[] num = new int[raw.length()];
for (int i = 0; i < raw.length(); i++) {
num[i] = Integer.parseInt(String.valueOf(list[i]));
}
for (int i: num) {
System.out.print(i);
}
Simple and modern solution
int[] result = new int[raw.length()];
Arrays.setAll(result, i -> Character.getNumericValue(raw.charAt(i)));
Line num[i] = (int[])list[i];
It should be num[i] = (int) list[i];
You are looping through the array so you are casting each individual item in the array.
The reason you got "garbage" is you were printing the int values in the num[] array.
char values are not a direct match for int values.
char values in java use UTF-16 Unicode.
For example the "3" char translates to 51 int
To print out the final int[] back to char use this loop
for(int i:num)
System.out.print((char) i);
I don't see anyone else mentioning the obvious:
We can skip the char array and go directly from String to int array.
Since java 8 we have CharSequence.chars which will return an IntStream so to get an int array, of the char to int values, from a string.
String raw = "1233983543587325318";
int[] num = raw.chars().toArray();
// num ==> int[19] { 49, 50, 51, 51, 57, 56, 51, 53, 52, 51, 53, 56, 55, 51, 50, 53, 51, 49, 56 }
There are also some math reduce functions on Intstream like sum, average, etc. if this is your end goal then we can skip the int array too.
String raw = "1233983543587325318";
int sum = raw.chars().sum();
// sum ==> 995
nJoy!

Categories