I have a method as below
public Object[][] createData() {
return new Object[][] {
{"data1"},{"data2"},{"data3"}
};
}
Now let's say I have multiple data (upto data50) in a properties file and I'm storing all the values in a list inside above mentioned method. What is the best way to return the object without hard coding the data values inside the method (Like data4, data5, data6....)
Can't you just use a loop?
Object[][] data = new Object[50][1];
for (int i = 0; i < 50; i++) {
data[i] = new Object[]{getData()};
}
data is an array of arrays (a "2D-array"). In other words, each element data[i] of data is itself an Object[]. Consequently, we can assign new Object[]{getData()} (an array) to data[i].
Related
So I'm trying to go through an arraylist of objects that all have a certain strength value and depending on their strength value, they go into the bigger 2d array based on that. So if their strength value is 0 then they go in the 0th array of the bigger one and this is what my code looks like so far
private ArrayList<Battleable> arr;
public BattleDeck() {
arr = new ArrayList<Battleable>();
for (Battleable creature: arr){
arr.add(creature);
}
}
public Battleable[][] export2Darray() {
//returns a two-dimensional ragged array where each row
// contains a deep copy of all of the Battleable objects
// in the BattleStack with the corresponding Level value
Battleable[][] retVal = new Battleable[10][];
int k = 0;
for (int i = 0; i<arr.size(); i++){
int levelOfObj = arr.get(i).getLevel();
if(levelOfObj == k) {
//insert it into retVal[0][0]
}
}
}
return retVal;
}
and I was wondering how I would do that? How do i syntax-tically say "get the obj that has strength 0 and put it in position 0 0 of my 2d array
A solution using Java 8 streams:
// group Battleables ArrayList by strength
Map<Integer, List<Battleable>> map =
arr.stream().collect(Collectors.groupingBy(Battleable::getStrength));
The result is a Map containing the Battleables as Lists with their strength as their key.
If you need the result as a jagged 2D array, sort the entries like this:
final Battleable[][] arrays = new Battleable[10][];
map.entrySet().forEach(entry -> {
arrays[entry.getKey()] = entry.getValue().toArray(new Battleable[entry.getValue().size()]);
});
Since arrays are of fixed size in Java, there is no clean way to add items to an array. You can resize the array each time by creating a new array each time, one larger than the last, and copying the data from the old array to the new array, but that would be messy and you would be reinventing a wheel called ArrayList. Modus Tollens has a good answer, but it uses some slightly advanced Java 8 concepts. Here's one way to write it without them:
public Battleable[][] export2Darray() {
Battleable[][] retVal = new Battleable[10][];
// create a map that will hold the items, arranged by level
Map<Integer, List<Battleable>> byLevel = new HashMap<>();
for (int i = 0; i < 10; i++) {
// initialize all levels with empty lists
byLevel.put(i, new ArrayList<>());
}
for (Battleable battleable : arr) {
int level = battleable.getLevel();
// get the list for this level and add to it
byLevel.get(level).add(battleable);
}
// Now we have a map from levels to lists of battleables;
// we need to turn each list into an array in our retVal
for (int level = 0; level < 10; level++) {
// get each list, convert it toArray and assign to slot in retVal
retVal[level] = byLevel.get(level).toArray(new Battleable[0]);
}
return retVal;
}
Here's a solution using ArrayLists, I am creating an ArrayList which will be referenced by strength, then inside of this I have another ArrayListwhich will have all of the Battleable objects of that strength level.
public ArrayList<ArrayList<Battleable>> exportBattleable() {
ArrayList<ArrayList<Battleable>> retVal = new ArrayList<ArrayList<Battleable>>();
for (int i = 0; i < arr.size(); i++){
retVal.get(arr.getLevel()).add(arr.get(i));
}
return retVal;
}
Now if you want to print all Battleable objects of strength = 3, you would do:
ArrayList<Battleable> strength3 = retVal.get(3);
for(Battleable battleable : strength3) {
System.out.println(battleable.toString());
}
This way you don't have to worry about re-sizing your arrays depending on how many Battleable objects you are adding in, same with strength levels, if you decide that instead of using strength levels from 0-9 that you wanted to use 0-20 you already have the ability to scale up or down.
array=[]
sent to servlet >>>>
///////// how i get [0]-[3] in array value in array [0-50]
for(????)
{ var A = get[0].toString;
var b = get[1].toString;
var c = get[2].toString;
var d = get[3].toString;
}
You can use Lists class from Guava
Object[] array = new Objects[50];
//... somehow fill array with real data
List<List<Object>> parts = Lists.partition(Arrays.asList(array), 4);
for(List<Object> part: parts){ //List 'part' will always contain not more than 4 elements
proccessPart(part); //passing elements to the method wich interacts with database
}
With the limited given information, If the question is how to processs an array which contains 50 objects with 4 untouched continuous objects sequentially
Object[] array = new Object[50];
//populate array
for(int i=3;i<50;i+=4) {
Object a = array[i-3];
Object b = array[i-2];
Object c = array[i-1];
Object d = array[i];
//variables may not be required as you can directly use array[i]
}
I'm searching for this problem since days and I can't seem to find a proper answer.
So I have an ArrayList of Arrays in form of Objects (ArrayList) filled with the result set of a SQL string. My goal is to convert the result of only one row into a one-dimensional Array of Objects.
I have tried several times my research results from this website, but the only knowledge I've made was how to convert a one-dimensional ArrayList to a simple array.
I hope you guys can help me in some ways. Thanks!
My table is looking like this:
sizeid | diameter
1 | 32
2 | 40
With the SQL-command "SELECT diameter FROM size" I'll get those two numbers 32 and 40, stored in a simple 2x1 table.
| 32 |
| 40 |
Now I want to have them in a one-dimensional Array.
the method to convert:
private Object[] getSizes() {
query = new SQLquery();
query.setSQLstring("SELECT diameter FROM size");
query.runQuery();
List<Object> sizeList = query.getRowData();
Object[] sizes = new Object[sizeList.size()];
// here I want to convert the List to an array..
return sizes;
}
the method to generate the ArrayList of the class SQLquery:
public void outputResult() {
try {
if (result != null) {
ResultSetMetaData meta = result.getMetaData();
columns = meta.getColumnCount();
columnNames = new Object[columns];
for (int i=1; i<=columnNames.length; i++) {
columnNames[i-1] = meta.getColumnName(i);
}
List<Object> rowData = new ArrayList<Object>();
while (result.next()) {
Object[] row = new Object[columns];
for (int j=0; j<= columns; j++) {
row[j-1] = result.getString(j);
}
rowData.add(row);
}
}
} catch (SQLexception e) {
System.out.println(e);
}
}
and the simple get-method of the class SQLquery:
public List<Object> getRowData() {
return rowData;
}
Apparently, your getRowData() method returns a List<Object> whereas it actually contains arrays. Although this looks strange since you say it always returns a list of arrays, I'll assume that's what you have.
You need a loop which goes over these "objects", downcasting them to Object[], and taking the first member.
Object[] sizes = new Object[sizeList.size()];
int i = 0;
for (Object o : sizeList) sizes[i++] = ((Object[]) o)[0];
return sizes;
You could use the approach what Marko Topolnik suggested.
However I would suggest to write your own "Table" class, which parses the result set and puts the values into an N*M dimensional array (or List) depending on your query. This way you can store meta information like the size of N or M dimension, etc.
I am writing a code where i have to add a 1d array in 2d array.
For example: I have a userlist array which will add data array in it
Double[][] userList = new Double[4][appName.size()];
Double[] data = new Double[appName.size()];
so user list will have something like this:
userlist={{1,2,3,4}, {2,3,4,7}, {0,0,1,2,}}
where {1,2,3,4}===> represents data array.
Problem: The problem that i am getting is that each time what data array returns just overwrite the whole thing in userlist with the new data.
for example:
if userlist={{1,2,3,4}, {2,3,4,7}} and data returns {0,0,4,5}
then my userlist becomes: {{0,0,4,5}, {0,0,4,5}, {0,0,4,5} }.
Code:
Double[][] userList = null;
userList = new Double[4][appName.size()];
String prevName = null;
Double[] data = new Double[appName.size()];
int count=0;
for(AuditInformationEntity e : auditInfoList)
{
//int count =0;
if(prevName== null || !prevName.equals(e.getDisplayName()) )
{
if(prevName!=null)
{
////====>> I think Something to be done here<========/////
userList[count++]=data;
}
//data = new ArrayList<Double>();
for(int i = 0 ; i<appName.size();i++)
data[i]=0d;
prevName = e.getDisplayName();
}
Double d = data[appName.indexOf(e.getAppName())];
if(d==null){
d=1d;
data[appName.indexOf(e.getAppName())]= d;
}
else
{
d++;
data[appName.indexOf(e.getAppName())]= d;
}
}
userList[count++]=data;
return userList;
You've correctly identified the problem line. Java doesn't technically have multidimensional arrays; instead, it has arrays of arrays. This means that when you say userList[i] = data, you're just telling Java to update the reference of userList[i] to point to the same data array. (This is called an aliasing bug, since you are thinking you're dealing with different arrays, but you're just calling the same array by different names.)
Instead, in this case it's probably better to do this:
int i;
double userList[][] = new double[numberOfArrays][];
double data[] = new double[4];
...
// inside a loop
// read into data
userList[i] = Arrays.copyOf(data);
This doesn't actually allocate the inside 4-element arrays when you create userList; it makes copies of each version of the data array when you're adding it.
I have 3 arraylist each have size = 3 and 3 arrays also have length = 3 of each. I want to copy data from arraylists to arrays in following way but using any loop (i.e for OR for each).
myArray1[1] = arraylist1.get(1);
myArray1[2] = arraylist2.get(1);
myArray1[3] = arraylist3.get(1);
I have done it manually one by one without using any loop, but code appears to be massive because in future I'm sure that number of my arraylists and arrays will increase up to 15.
I want to copy the data from arraylists to arrays as shown in the image but using the loops not manually one by one?
How about this?
List<Integer> arraylist0 = Arrays.asList(2,4,3);
List<Integer> arraylist1 = Arrays.asList(2,5,7);
List<Integer> arraylist2 = Arrays.asList(6,3,7);
List<List<Integer>> arraylistList = Arrays.asList(arraylist0, arraylist1, arraylist2);
int size = 3;
int[] myArray0 = new int[size];
int[] myArray1 = new int[size];
int[] myArray2 = new int[size];
int[][] myBigArray = new int[][] {myArray0, myArray1, myArray2};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
myBigArray[i][j] = arraylistList.get(j).get(i);
}
}
To explain, since we want to be able to work with an arbitrary size (3, 15, or more), we are dealing with 2-dimensional data.
We are also dealing with array and List, which are slightly different in their use.
The input to your problem is List<Integer>, and so we make a List<List<Integer>> in order to deal with all the input data easily.
Similarly, the output will be arrays, so we make a 2-dimensional array (int[][]) in order to write the data easily.
Then it's simply a matter of iterating over the data in 2 nested for loops. Notice that this line reverses the order of i and j in order to splice the data the way you intend.
myBigArray[i][j] = arraylistList.get(j).get(i);
And then you can print your answer like this:
System.out.println(Arrays.toString(myArray0));
System.out.println(Arrays.toString(myArray1));
System.out.println(Arrays.toString(myArray2));
You need to have two additional structures:
int[][] destination = new int [][] {myArray1, myArray2,myArray3 }
List<Integer>[] source;
source = new List<Integer>[] {arraylist1,arraylist2,arraylist3}
myArray1[1] = arraylist1.get(1);
myArray1[2] = arraylist2.get(1);
myArray1[3] = arraylist3.get(1);
for (int i=0;i<destination.length;i++) {
for (int j=0;j<source.length;j++) {
destination[i][j] = source[j].get(i);
}
}
If you cannot find a ready made API or function for this, I would suggest trivializing the conversion from List to Array using the List.toArray() method and focus on converting/transforming the given set of lists to a another bunch of lists which contain the desired output. Following is a code sample which I would think achieves this. It does assume the input lists are NOT of fixed/same sizes. Assuming this would only make the logic easier.
On return of this function, all you need to do is to iterate over the TreeMap and convert the values to arrays using List.toArray().
public static TreeMap<Integer, List<Integer>> transorm(
List<Integer>... lists) {
// Return a blank TreeMap if not input. TreeMap explanation below.
if (lists == null || lists.length == 0)
return new TreeMap<>();
// Get Iterators for the input lists
List<Iterator<Integer>> iterators = new ArrayList<>();
for (List<Integer> list : lists) {
iterators.add(list.iterator());
}
// Initialize Return. We return a TreeMap, where the key indicates which
// position's integer values are present in the list which is the value
// of this key. Converting the lists to arrays is trivial using the
// List.toArray() method.
TreeMap<Integer, List<Integer>> transformedLists = new TreeMap<>();
// Variable maintaining the position for which values are being
// collected. See below.
int currPosition = 0;
// Variable which keeps track of the index of the iterator currently
// driving the iteration and the driving iterator.
int driverItrIndex = 0;
Iterator<Integer> driverItr = lists[driverItrIndex].iterator();
// Actual code that does the transformation.
while (driverItrIndex < iterators.size()) {
// Move to next driving iterator
if (!driverItr.hasNext()) {
driverItrIndex++;
driverItr = iterators.get(driverItrIndex);
continue;
}
// Construct Transformed List
ArrayList<Integer> transformedList = new ArrayList<>();
for (Iterator<Integer> iterator : iterators) {
if (iterator.hasNext()) {
transformedList.add(iterator.next());
}
}
// Add to return
transformedLists.put(currPosition, transformedList);
}
// Return Value
return transformedLists;
}