If it's possible to convert arraylist of string (ArrayList<String[]>) to array of integer (int[]), is it possible to convert arraylist of arrays of string(ArrayList<String[]>) to array of integer (int[])?
In Java 8:
list.stream().mapToInt(Integer::parseInt).toArray();
edit
Since the question was edited with List<String[]> instead of List<String>, a solution would be:
list.stream().flatMap(Arrays::stream).mapToInt(Integer::parseInt).toArray();
i have modified the code according to your edited answer,do reply if this is what you want.
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
ArrayList<String[]> strArrayList= new ArrayList<String[]>();
String[] str1={"16","1421","1577"};
String[] str2={"15","1451","1461","6556"};
String[] str3={"157","8751","1136","556","879"};
strArrayList.add(str1);
strArrayList.add(str2);
strArrayList.add(str3);
int sizeOfArr=0;
int i=0;
for (String[] s : strArrayList)
{
sizeOfArr+=s.length;
}
int[] ArrayRes = new int[sizeOfArr];
for (String[] s : strArrayList)
{
if(s.length>0){
for (String s1 : s){
ArrayRes[i] = Integer.parseInt(s1);
System.out.println(ArrayRes[i]);
i++;
}
}
}
}
}
run the below code,i hope it meets you requirement.
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
ArrayList<String> strArrayList= new ArrayList<String>();
strArrayList.add("1");
strArrayList.add("11");
strArrayList.add("111");
strArrayList.add("12343");
strArrayList.add("18475");
int[] ArrayRes = new int[strArrayList.size()];
int i = 0;
int x = 0;
for (String s : strArrayList)
{
ArrayRes[i] = Integer.parseInt(s);
System.out.println(ArrayRes[i]);
i++;
}
}
}
Output:
1
11
111
12343
18475
Further to my comment, you'll need to work out how to map from 2D to 1D array.
Here's a suggestion which results in Integer[] rather than int[] but you might not worry about that:
public static void main(String[] args) {
ArrayList<String[]> arrList = new ArrayList<String[]>();
//fill it
arrList.add(new String[] {"11","12","13","14","15"});
arrList.add(new String[] {"21","22","23","24","25"});
arrList.add(new String[] {"31","32","33","34","35"});
arrList.add(new String[] {"41","42","43","44","45"});
arrList.add(new String[] {"41","52","53","54","55"});
//convert it
ArrayList<Integer> ints = new ArrayList<Integer>();
for (String[] array : arrList) {
for (String str : array) {
ints.add(Integer.parseInt(str));
}
}
Integer[] result = ints.toArray(new Integer[] {});
for (int i : result)
System.out.println(i);
}
It is possible if all the Strings can be parsed to integers correctly.
Iterate over the list and in the list over the array. Parse the Strings to Integers (e.g. with Integer.parseInt(someString);) and store the integervalues in the integer array.
Of course you'll have to find the total number of values in the list to initialize the array.
Related
given an array
String original[]={"string0,10","string1,45","string2,3", "string3,67"};
how would I use the comma as a delimeter to create another array with only the names?
I need an array that looks something like this:
String result[]={"string0","string1","string2", "string3"};
You can use streams and map from java 8 to do it:
String[] strings = Arrays.stream(test)
.map(string -> string.split(",")[0])
.toArray(String[]::new);
public static void main(String[] args) {
String original[]={"string0,10","string1,45","string2,3", "string3,67"};
int len = original.length;
String result[] = new String[len];
for(int i=0; i<len;i++) {
result[i] = original[i].split(",")[0];
}
System.out.println(Arrays.toString(result));
}
DeclareString result[] array
Iterate the array
Split the record for every Iteration using , as delimiter
Now the split operation will return the array of size 2. It contains name at index 0.
assign the value the result array.
import java.util.Arrays;
import java.util.stream.Collectors;
public class ArraySubstring {
public static void main (String args[]) {
String test[]={"string0,10","string1,45","string2,3", "string3,67"};
String test2[] = Arrays.stream(test).map(s -> s.substring(0, s.indexOf(","))).toArray(String[]::new);
for (String s : test2) {
System.out.println(s);
}
}
}
import java.util.ArrayList;
public class LengthsOfStrings
{
public static ArrayList<Integer> lengths(ArrayList<String> list) {
ArrayList<Integer> lengthList = new ArrayList<Integer>();
list.length();
return lengthList;
}
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<String>();
list.add("Ciao");
list.add("Moi");
list.add("Benvenuto!");
list.add("badger badger badger badger");
ArrayList<Integer> lengths = lengths(list);
System.out.println("The lengths of the Strings: " + lengths);
}
}
I was thinking something like this, but I don't know what to fill in the list.length(); with.
public static ArrayList<Integer> lengths(ArrayList<String> list) {
ArrayList<Integer> lengthList = new ArrayList<Integer>();
for (String s : list)
lengthList.add(s.length());
return lengthList;
}
Your lengths method should iterate over the input array, and for each String in it, add that String's length (which you get by calling length() method of String) to the output array.
Java 8:
public static List<Integer> lengths(List<String> list) {
return list.stream()
.map(String::length)
.collect(Collectors.toList());
}
Agree with Eran, and in case you want it in short:
for(int i = 0; i < list.size(); i++)
lengthList.add(i, list.get(i).length());
Do I have to loop through each element to convert ArrayList<String[]> to String[][] or is there a more efficient way?
Just get the contents as an array
List<String[]> list = new ArrayList<>();
...
String[][] array = list.toArray(new String[0][0]); // the size here is not important, the array is just an indication of the type to use
You can use .toArray(T[]) for this.
public static void main(String[] args) {
List<String[]> l = new ArrayList<String[]>();
String[] a = {"lala", "lolo"};
String[] b = {"lili", "lulu"};
l.add(a);
l.add(b);
String[][] r = new String[l.size()][];
r = l.toArray(r);
for(String[] s : r){
System.out.println(Arrays.toString(s));
}
}
Output:
[lala, lolo]
[lili, lulu]
I am doing a project in android ,and i have a problem My array list values like this
[men-1, men-2, men-3, women-1, women-2, women-3]
How can I split these values in different arrays? i.e how can I save men-1,men-2,men-3 in one array and women-1,women-2,women-3 in other array?
It is hard to help you without details but you should probably
create separate Lists for man and woman elements,
iterate over all elements of your lists
in case of list is string you can determine its gender using element.startsWith("man")
in case elements are objects of Man or Woman classes you can use instanceof operator like if (element instanceof Man){listOfMans.add(element)}
now if you want to place ell elements in separate arrays you can use toArray(T[] array) method from each List instance.
the below code may help you
import java.util.Arrays;
public class Test{
public static void main(String[] args) {
String[] input = new String[] {"men-1", "men-2", "men-3", "women-1", "women-2", "women-3"};
int arr1Size=getCount(input, "women");
String[] arr1 = new String[arr1Size];
String[] arr2 = new String[input.length-arr1Size];
int i=0,j=0;
for(String str: input){
if(str.contains("women")){
arr1[i] = str;
i++;
}else{
arr2[j] = str;
j++;
}
}
System.out.println(Arrays.deepToString(arr1));
System.out.println(Arrays.deepToString(arr2));
}
public static int getCount(String[] input, String find){
int count=0;
for(String str: input){
if(str.contains(find)){
count++;
}
}
return count;
}
}
If those are the object of a class then you can easily do it using instanceOf operator... Otherwise below code can help you.. you can do it using arrays only as well as using arraylist
/**
*
*/
package com.sharique.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* #author Sharique
*
*/
public class Test {
/**
* #param args
*/
//List<Integer> list = new ArrayList<>();
//int[] arr = new int[10];
//int[] ar1= arr.clone();
public void usingArrays(){
StringBuffer sb1 = new StringBuffer("Men");
String[] arrays = {"Men-1","Men-2","Men-3","Women-1","Women-2","Women-3"};
String[] arrOfMen = new String[3];
String[] arrOfWomen = new String[3];
String str=null;
int count1=0;
int count2=0;
for(int i=0;i<arrays.length;i++){
str=arrays[i];
if(str.contains(sb1)){
arrOfMen[count1++]=str;
}else{
arrOfWomen[count2++]=str;
}
}
for(int i=0;i<arrOfMen.length;i++)
System.out.print(arrOfMen[i]+" ");
//For a new Line
System.out.println();
for(int i=0;i<arrOfWomen.length;i++)
System.out.print(arrOfWomen[i]+" ");
}
public void usingArrayList(){
String[] arrays1 = {"Men-1","Men-2","Men-3","Women-1","Women-2","Women-3"};
List<String> list = new ArrayList<>(Arrays.asList(arrays1));
String[] arrays2 = new String[3];
StringBuffer sb = new StringBuffer("Women");
int count=0;
String str=null;
Iterator<String> iterator = list.iterator();
while(iterator.hasNext()){
str =iterator.next();
if(str.contains(sb)){
arrays2[count++] = str;
iterator.remove();
}
}
//for a new line
System.out.println();
arrays1 = list.toArray(new String[list.size()]);
for(int i=0;i<arrays1.length;i++)
System.out.print(arrays1[i]+" ");
//for a new line
System.out.println();
for(int i=0;i<arrays2.length;i++)
System.out.print(arrays2[i]+" ");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Test test = new Test();
test.usingArrays();
test.usingArrayList();
}
}
I am new to java programming. My question is this I have a String array but when I am trying to convert it to an int array I keep getting
java.lang.NumberFormatException
My code is
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
int i=0;
for(String str:strings){
intarray[i]=Integer.parseInt(str);//Exception in this line
i++;
}
}
Any help would be great thanks!!!
Suppose, for example, that we have a arrays of strings:
String[] strings = {"1", "2", "3"};
With Lambda Expressions [1] [2] (since Java 8), you can do the next ▼:
int[] array = Arrays.asList(strings).stream().mapToInt(Integer::parseInt).toArray();
▼ This is another way:
int[] array = Arrays.stream(strings).mapToInt(Integer::parseInt).toArray();
—————————
Notes
1. Lambda Expressions in The Java Tutorials.
2. Java SE 8: Lambda Quick Start
To get rid of additional whitespace, you could change the code like this:
intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line
To help debug, and make your code better, do this:
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
int i=0;
for(String str:strings){
try {
intarray[i]=Integer.parseInt(str);
i++;
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Not a number: " + str + " at index " + i, e);
}
}
}
Also, from a code neatness point, you could reduce the lines by doing this:
for (String str : strings)
intarray[i++] = Integer.parseInt(str);
Another short way:
int[] myIntArray = Arrays.stream(myStringArray).mapToInt(Integer::parseInt).toArray();
Since you are trying to get an Integer[] array you could use:
Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
Your code:
private void processLine(String[] strings) {
Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
}
Note, that this only works for Java 8 and higher.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class array_test {
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
String[] s_array = line.split(" ");
/* Splitting the array of number
separated by space into string array.*/
Integer [] a = new Integer[s_array.length];
/Creating the int array of size equals to string array./
for(int i =0; i<a.length;i++)
{
a[i]= Integer.parseInt(s_array[i]);// Parsing from string to int
System.out.println(a[i]);
}
// your integer array is ready to use.
}
}
This is because your string does not strictly contain the integers in string format. It has alphanumeric chars in it.
public static int[] strArrayToIntArray(String[] a){
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = Integer.parseInt(a[i]);
}
return b;
}
This is a simple function, that should help you.
You can use him like this:
int[] arr = strArrayToIntArray(/*YOUR STR ARRAY*/);
private void processLine(String[] strings) {
Integer[] intarray=new Integer[strings.length];
for(int i=0;i<strings.length;i++) {
intarray[i]=Integer.parseInt(strings[i]);
}
for(Integer temp:intarray) {
System.out.println("convert int array from String"+temp);
}
}