Java - making an array using for loop - java

Is it possible in Java to make an array in a style similar to this, i have been searching for a while and haven't found anything.
int[] foo = {
for(String arg:args)
return Integer.parseInt(arg);
};

No, but you can do this instead :
int[] foo = new int[args.length];
for(int i = 0; i < foo.length; i++) {
foo[i] = Integer.parseInt(args[i]);
}

Not exactly, but try this.
int[] foo = new int[args.length]; //Allocate the memory for foo first.
for (int i = 0; i < args.length; ++i)
foo[i] = Integer.parseInt(args[i]);
//One by one parse each element of the array.

With Java 8, it can be done like this:
int[] foo = Stream.of(args).mapToInt(str -> Integer.parseInt(str)).toArray();

Kind of... Since Java 8 we have streams which can simulate loop and allow us to do things like
int[] arr = Arrays.stream(args).mapToInt(s -> Integer.parseInt(s)).toArray();
or its equivalent using method references
int[] arr = Arrays.stream(args).mapToInt(Integer::parseInt).toArray();

int[] foo = new int[arg.length];
for (int i =0;i<args.length;i++) foo[i]=Integer.parseInt(args[i]);

With array no, but you can do something similar with List:
final String args[] = {"123", "456", "789"};
List<Integer> list = new LinkedList<Integer>(){
{
for (String arg: args){
add(Integer.parseInt(arg));
}
}
};
System.out.println(list); // [123, 456, 789]
With array you have to do the following:
int[] foo = new int[args.length];
for (int i = 0; i < foo.length; i ++) {
foo[i] = Integer.parseInt(args[i]);
}

Related

Is it possible to go into an array and take only some values of that array and make a new array?

For example, lets say that I have an array
String[] array = {"hello", "bye", "yo", "ufc", "nba", "kobe"};
Is it possible to use a for loop to go into the array and make a new array with every 3 words so they new arrays would be:
String[] newArray = {"hello", "bye", "yo"}
String[] newArray2 = {"ufc", "nba", "kobe"}
This is java btw. Thank you.
String[] newArray = new String[3];
for (int i = 0 ; i < nRecords ; i++) {
newArray[i] = array[i + startRecord];
}
You should decide how to store all the arays. You can't generate variables with new name. You could use 2D array String[][] arrays;
full sample:
int nRecords = 3;
String[] array = {"hello", "bye", "yo", "ufc", "nba", "kobe"};
int nArrays = array.length / nRecords;
String[][] newArrays = new String[nArrays][];
for (int k = 0; k < nArrays; k ++) {
newArrays[k] = new String[nRecords];
for (int i = 0 ; i < nRecords ; i++) {
newArrays[k][i] = array[i + k * nRecords];
}
}
Here's a complete working example:
public static void main(String[] args)
{
String[] array = {"hello", "bye", "yo", "ufc", "nba", "kobe"};
List<String[]> every3 = new ArrayList<>();
for (int i = 0; i < array.length; )
{
int len = (i < array.length - 3) ? 3 : array.length - i;
String [] newArr = new String [len];
for (int j = 0; j < len; j++)
{
newArr[j] = array[i++];
}
every3.add(newArr);
}
for (String [] arr : every3)
{
System.out.println(Arrays.toString(arr));
}
}
Outputs:
[hello, bye, yo]
[ufc, nba, kobe]
Note: This code also works if the length of the main array is not a multiple of 3;
You can use Use Arrays.copyOfRange
Code
String[] newArray = Arrays.copyOfRange(array, 0, 3);
String[] newArray2 = Arrays.copyOfRange(array, 3, array.length);
result
//newArray
hello bye yo
//newArray2
ufc nba kobe

How can I backfill a Java string array based on two other arrays?

I have two arrays:
String[] ArrayA = {"9","1","4","2","3"};
String[] ArrayB = {"9","2","8"};
How do I get a new array like the following
String[] ArrayC = {"9","2","8","A","A"};
The logic is to create a new ArrayC of length equal to ArrayA and backfill the remaining array elements (ArrayA length minus ArrayB length = 2) difference with "A".
Read the javadoc of Arrays.
arrayC = Arrays.copyOf(arrayB, arrayA.length);
Arrays.fill(arrayC, arrayB.length, arrayA.length, "A");
You could just iterate over arrayB and copy it:
String[] arrayA = {"9","1","4","2","3"};
String[] arrayB = {"9","2","8"};
String[] arrayC = new String[arrayA.length];
// copy arrayB:
for (int i = 0; i < arrayB.length; ++i) {
arrayC[i] = arrayB[i];
}
// fill in the remainder:
for (int i = arrayB.length; i < arrayA.length; ++i) {
arrayC[i] = "A";
}
Based on the previous posted code,this is a generic method which satisfy your need, it takes 3 params , two arrays and the word to be used to be used in replacing empty elements
public static String [] fill(String [] arrayA, String[] arrayB ,String word) {
String[] toBeCopied = null ;
int size ;
if( arrayA.length > arrayB.length ) {
size = arrayA.length ;
toBeCopied = arrayB ;
} else {
size = arrayB.length ;
toBeCopied = arrayA ;
}
String[] arrayC = new String[size];
for (int i = 0; i < toBeCopied.length; ++i) {
arrayC[i] = toBeCopied[i];
}
for (int i=toBeCopied.length;i<arrayC.length ;i++ )
arrayC[i] = word;
return arrayC ;
}

Need Help Adding an Integer Array to an Array List in Processing

Ok... So I am in the middle of a project, and I've hit a bit of a wall. If anyone could please explain how to add an integer array to an ArrayList of integer Arrays, I would greatly appreciate it. This is in processing, the javascript version more specifically. I have tested and everything works right up to 'symbols.get(i).add(tempArray). If I print tempArray right before that line it gives me '6 10 16 10 16 20', as it should. And no, it's not just the println(symbols) statement, I also tried just 'println("blah");'and that did not show up in the output, so something is going awry at the .get line.
size(850,250);
String[] myList = new String[100];
ArrayList<Integer[]> symbols = new ArrayList<Integer[]>();
int[] tempArray = new int[];
String numbers = ("6,10,16,10,16,20\n1,25,21,13,3,15\n6,5,20,6,21,20");
myList = (split(numbers, "\n"));
int j = myList.length();
for(int i = 0; i<j; i++)
{
tempArray = int(split(myList[i], ','));
symbols.get(i).add(tempArray);
}
println(symbols);
... I have also tried the following in place of 'symbols.get(i).add(tempArray);'
for(int a = 0; a < tempArray.length(); a++)
{
symbols.get(i[a]) = tempArray[a];
}
println(symbols);
... I have also tried
for(int a = 0; a < tempArray.length(); a++)
{
symbols.get(i) = tempArray[a];
}
println(symbols);
... and
for(int a = 0; a < tempArray.length(); a++)
{
symbols[i][a] = tempArray[a];
}
println(symbols);
I'm out of guesses and tries, any help would be appreciated.
First get the Array of integer by using the get method on the ArrayList, then add [index] to specify what to add at which index of the returned Array.
symbols.get(i)[a] = tempArray[a];
There are some mistakes. The key one is that you can't add int[] to the list expecting Integer[]. Here, see the comments on the code:
void setup()
{
size(850, 250);
String[] myList = new String[100];
ArrayList<Integer[]> symbols = new ArrayList<Integer[]>();
// you can't init an array without a inintial dimension
//int[] tempArray = new int[];
int[] tempArray;
String numbers = ("6,10,16,10,16,20\n1,25,21,13,3,15\n6,5,20,6,21,20");
myList = (split(numbers, "\n"));
//length is not a method... no parenthesis here
//int j = myList.length();
int j = myList.length;
for (int i = 0; i<j; i++)
{
tempArray = int(split(myList[i], ','));
// you cant add an int[] to an Integer[] arrayList
// you gotta either change the arraylist type or convert the ints to Integers
// also just use .add(). not get().add() it's a one dimension list
symbols.add(parseArray(tempArray));
println(symbols.get(i) );
println("--");
}
}
//convenience function..
Integer[] parseArray(int[] a) {
Integer[] b = new Integer[a.length];
for (int i = 0; i<a.length; i++) {
b[i] = Integer.valueOf(a[i]);
}
return b;
}
and the other way...
void setup()
{
size(850, 250);
String[] myList = new String[100];
ArrayList<int[]> symbols = new ArrayList<int[]>();
// you can't init an array without a inintial dimension
//int[] tempArray = new int[];
int[] tempArray;
String numbers = ("6,10,16,10,16,20\n1,25,21,13,3,15\n6,5,20,6,21,20");
myList = (split(numbers, "\n"));
//length is not a method... no parenthesis here
//int j = myList.length();
int j = myList.length;
for (int i = 0; i<j; i++)
{
tempArray = int(split(myList[i], ','));
symbols.add(tempArray);
println(symbols.get(i) );
println("--");
}
}

Arraylist<String[]> how to access?

I have an ArrayList< String[] >, but how do you get String[] back to normal values?
This is what I got (of course not finished), and I want it to return an Object[][] with my values. Is it possible?
public Object[][] noName(String[] col) {
ArrayList<String[]> arrlist = new ArrayList<String[]>();
for (int i = 0; i < col.length; i++) {
arrlist.add(createColumnList(col[i]));
}
// How to get it into an Object[][]?
// Something made up..
return new Object[0][0];
}
createColumnList is just a method to create an array from different columns in a XML
It's a one-liner, actually:
return arrlist.toArray(new Object[arrlist.size()][]);
But it would be even simpler (and more efficient) to start with the array directly:
final Object[][] ret = new Object[col.length][];
for (int i = 0; i < col.length; i++) ret[i] = createColumnList(col[i]);
return ret;
Try it
final Object[][] obj = new Object[col.length][];
for (int i = 0; i < col.length; i++) obj[i] = createColumnList(col[i]);
return obj;
You just to loop and Object array to store. Here is the code to add to your comment place:
List<String[]> arrList = new ArrayList<String[]>();
Object[][] objArray = new Object[ arrList.size() ][ col.length ];
for ( int i = 0; i < arrList.size(); i++ )
objArray[ i ] = arrList.get( i );
I think that will be what you want.
First of all there is an .toArray function for Arraylist.
alternatifly you can do this.
Object[][] objarr = new Object[arrlist.size()][arrlist.get(0).length]
for(int i=0;i<arrlist.size();i++){
for(int j=0;j<arrlist.get(i).size(),j++){
objarr[i][j]=arrlist.get(i)[j];
}
}
This simply loops over every element in the array and puts them in your new array. Chance Object[][] into String[][] if you want to put it in a String array instead.
I think this should also be possible but am a bit fuzy on the rules of recasting arrays.
Object[][] objarr = new Object[arrlist.size()][];
for(int i=0;i<arrlist.size();i++){
objarr=arrlist.get(i);
}

naming arrays in a loop

i'm out of my league.
ok so if i can do this:
int[]teams = new int[3];
for (int i = 0; i < 3; i++)
{
teams[i] = i;
}
how do i do the similar thing but naming multiple arrays, ie
for (int i = 0; i < 3; i++)
{
int[]i = new int[3];
}
I have read you can't name an array with a variable so I can't just see how to produce arrays with different names (basically more than one) using a loop.
Thanks
You'd do the following (Java):
int teams[][] = new teams[3][3]
You'd do the following (C++):
int** teams = new int*[3];
for(int i=0; i<3; i++){
teams[i] = new int[3];
}
or you could just do
int teams[3][3];
for(int i=0; i<3; i++){
for(int j=0; j<3; j++){
teams[i][j] = //whatever you want
}
}
Edit in response to your comment below:
What you're looking for is a MultiMap. There you're going to get:
MultiMap foo = new MultiMap();
foo.put("Bob", 1);
foo.put("Bob", 2);
etc...
You can make an array of arrays (sometimes called a multidimensional array):
int [][] arr = new int[137][42];
You cannot dynamically generate variable names, but you can achieve the same effect with a Map:
//Store mappings from array name (String) to int arrays (int[])
Map<String, int[]> namedArrays = new HashMap<String, int[]>();
for (int i = 0; i < 3; i++)
{
//This is going to be the name of your new array
String arrayName = String.valueOf(i);
//Map an new int[] to this name
namedArrays.put(arrayName, new int[3]);
}
//If you need to access array called "2" do
int[] array2 = namedArrays.get("2")
The advantage of doing it this way is that you can have multiple arrays with same names as long as they are in different maps. But note that when you map two or more arrays to the same name in the same map, the previous array will be overriden (lost).

Categories