declaring multiple java arrays in a loop - java

Hi guys thanks for helping in advance this is not the real code it is just the idea i want to reach
for (int i = 1, i< some number ; i ++ )
float [][] sts + i = new float[9][9];
The idea is to have 2 dimensional arrays with dynamic names initializing in a loop
sts1
sts2
sts3
.
.
.
.
.

For your problem, where naming is sequential based on the value of i, an ArrayList could do the job as you can iterate over it.
However, a more general approach that enables you accessing your arrays by some String name (even if this was random and not sequential as in your case) would be to use a Map<String, float[][]>, where the key String of the Map is the name you have given to your array.
Map<String, float[][]> myMap = new HashMap<String, float[][]>();
for(int i = 0; i < someNumber; ++i)
{
myMap.put("sts" + i, new float[9][9]);
}
then access each array by myMap.get(_aName_);

If you create every 2 dimensional array in the loop, then the variabl (like sts1) will only be local to the loop. So after the loop the variable is out of scope (but I think you want to use them after the loop, that's why you want different names). So to use the created variables, you have to use an array. And if you use an array, the question of naming ceases.
ArrayList<float[][]> l = new ArrayList<float[][]>();
for(int i = 0; i < someNumber; ++i)
{
l.add(new float[9][9]);
}

You can't create variable names dynamically in Java. Just do this
float[][][] sts = new float[someNumber][9][9];
Then you can use sts[0], sts[1] where you wanted to use sts1, sts2 etc.

Related

Iterate through an list of objects and run a function for each - Java

I'm wondering for the simplest method for how to run a specific function for each object in an array (or other list type)
My goal is to be able create a list of objects, and have each object run a specific function as it passes through the iterator.
I've tried a for loop on an arraylist
for (int i = 0; i < testList.size(); i++)
{
this = textList.get(i);
this.exampleFunction();
}
But this gives me a 'Variable expected' error
Assuming you're using Java 8+, and you have a Collection<TypeInList> you could call Collection.stream() and do a forEach on that. Like,
testList.stream().forEach(TypeInList::function);
Your current approach is trying to do things with this that cannot be done. It could be fixed like,
for (int i = 0; i < testList.size(); i++)
{
TypeInList that = testList.get(i); // this is a reserved word.
that.function();
}
or
for (TypeInList x : testList) {
x.function();
}
There are multiple ways to iterate through a list, but the easiest I personally find is like this:
Assuming that your list contains String objects e.g.:
List<String> list = new ArrayList();
list.add("Hello");
list.add("World");
for(String current : list){
System.out.println(current);
}
The loop will iterate twice, and console will output the following:
Hello
World
This approach doesn't rely on indexes (as how you're using it in your question), as such I find it easy to use for iterating through a single list.
However the disadvantage is that if you have 2 separate lists that you would like to iterate through, the lack of indexes makes it a bit more complicated. The easier approach for iterating through multiple lists would be using the traditional approach, something like this:
for(int i=0; i<list.size(); i++){
int x = list1.get(i);
int y = list2.get(i);
}
As such your use-case really determines the ideal method you can adopt.

wanted put array list items into variables using loop

i am dynamically adding items to array-list after i wanted to
Initialize Variables using this array-list items
my array-list is
ArrayList<String> dayCountList = new ArrayList<String>();
i try to do like this but it doesn't work
for (int i = 0; i < dayCountList.size() ;i++) {
double day+"i" = Double.parseDouble(dayCountList.get(i));
}
You can create a array or array list of double type like this.
ArrayList<String> dayCountList = new ArrayList<String>();
.
.
double day[]=new double[dayCountList.size()];
// now use your loop like this
for (int i = 0; i < dayCountList.size() ; i++) {
day[i] = Double.parseDouble(dayCountList.get(i));
}
Now you can call your variables like day[0], for first element
day[1] ,for second and so on.
Hope this helped you.
If you are doing this, then you probably did not understand the purpose of array lists is. One purpose of array list is exactly to avoid creating a whole bunch of variables named day1, day2, day3 and so on.
You seem like you want to transform every element in the array list to a doubles. Why not create another ArrayList<Double> or double[] to store the transformed elements? Instead of writing day1, day2, you can say days.get(0), days.get(1) in the case of array lists. With arrays, you can do days[0], days[1] and so on.
ArrayList<Double> days = dayCountList.stream()
.mapToDouble(Double::parseDouble)
.boxed()
.collect(Collectors.toList());
// or
double[] days = dayCountList.stream()
.mapToDouble(Double::parseDouble).toArray()

Looking for a workaround for dynamic variable declaration in a for loop

I have a number of repetitions of a task I would like to put in a for loop. I have to store a time series object as an IExchangeItem, a special class in openDA (a data assimilation software).
This is one of the tasks (that works):
HashMap<String, TimeSeries> items = new LinkedHashMap<String, TimeSeries>();
...
TimeSeries tsc1Q = new TimeSeries(time,value);
id = "Q1";
tsc1Q.setId(id);
this.items.put(id,tsc1Q);
IExchangeItem c1Q = new TimeSeries(tsc1Q);
What changes across the tasks is the id of the time series object and the name of IExchangeItem. I have to create a new IExchangeItem object for each time series.
This is what I tried in the for loop:
HashMap<String, TimeSeries> items = new LinkedHashMap<String, TimeSeries>();
...
TimeSeries temp;
for (int i = 0; i<readDataDim[0]; i++) {
value[0] = values[i];
id = exchangeItemIDs[i];
temp = new TimeSeries(time,value);
temp.setId(id);
this.items.put(id,temp);
IExchangeItem <??> = new TimeSeries(temp); //* How can I handle this line?
}
I know I cannot use dynamic variable names in java and that arrays, lists, or maps are commonly used to work around this issue (this is why I used <??> in the code snippet above. However, I'm a relative beginner with java and I have no clue how I can work around this specific problem since I have to have a new invocation of IExchangeItem for each time series.
From here I take it that my IExchangeItem created in the for loop will not be accessible outside the for loop so how can I initialise n replicates of IExchangeItem outside the for loop?
Edit:
Does a HashMap create n instances of IExchangeItem if I try something like this?
HashMap<String,IExchangeItem> list = new LinkedHashMap<String,IExchangeItem>();
Just one suggestion, try to write a separate method when you can pass the size of the array or a fixed number (based on array), then you created a hashMap and add that many number of instances with its keys, and values, cannot post this as a comment and hence posting it as an answer.
Try to create a new method using the value of readDataDim[0] value,
public Map<String, IExchangeItem> createAndInitialzeMap(int maxValue) {
Map<String, IExchangeItem> map = new HashMap<>();
String temp = "tempName";
for(int i =0; i < maxValue ; i ++ ) {
map.put(temp+i, new IExchangeItem());
}
return map;
}
return this way you can initialize your map along with its variable name and you can use it in your app anywhere. However I would consider refactoring if such code exists and time permits.
One more thing you should read about hashMap. :) :)

Can I iterate over two arrays at once in Java?

For one array I can iterate like this:
for(String str:myStringArray){
}
How can I iterate over two arrays at once?
Because I am sure these two's length are equal.I want it like the following:
for(String attr,attrValue:attrs,attrsValue) {
}
But it's wrong.
Maybe a map is a good option in this condition, but how about 3 equal length arrays? I just hate to create index 'int i' which used in the following format:
for(int i=0;i<length;i++){
}
You can't do what you want with the foreach syntax, but you can use explicit indexing to achieve the same effect. It only makes sense if the arrays are the same length (or you use some other rule, such as iterating only to the end of the shorter array):
Here's the variant that checks the arrays are the same length:
assert(attrs.length == attrsValue.length);
for (int i=0; i<attrs.length; i++) {
String attr = attrs[i];
String attrValue = attrsValue[i];
...
}
You can do it old fashion way.
Assuming your arrays have same sizes:
for(int i = 0; i < array1.length; i++) {
int el1 = array1[i];
int el2 = array2[i];
}
In Scala there is an embedded zip function for Collections, so you could do something like
array1 zip array2
but it's not yet ported to Java8 Collections.
Foreach loop has many advantages but there are some restriction are also there.
1: You can iterate only one class(which implements Iterable i/f) at one time.
2: You don't have indexing control. (use explicit counter for that.)
For your problem use legacy for loop.

Inversed array but not a hashmap

In Java, I have an unsorted int[] values = new int[100]; array. All the values are unique (different) and they are uncomparable (no way to sort). Can I construct a kind of inversed function which will give me an index of a certain value in the array if I specify that value?
Currently done it using a hashmap:
IntIntMap indices = new IntIntOpenHashMap(100, 1);
for (int i = 0; i < 100; i++) {
indices.put(values[i], i);
}
Any other solution? Would prefer a faster one.
Yes, you could create your own hash function or research a specific one for your case. It depends on the structure of the values and whether this is truly a bottleneck in the program.

Categories