Get data from a Collection of maps with 2 int as parameters - java

I have a variable like:
Collection<Map<String, String>> allFieldValues;
In this variable I have all the data of a sqlite Table, each map of the collection represents a row of the table.
Now I have to take the data of a specific cell, my parameters are 2 ints (row number, column number), so I am trying something like this:
Iterator<Map<String, String>> iter = allFieldValues.iterator();
for (int i = 0; i == givenRowAsParameter; i++)
{
iter.next();
}
And thats it, the iter that I get out of the loop its supossed to be the row that I want, but I can't take another Iterator from that Iterator to search for the column, neither I can't get a specific object of the iterator with just an int as a parameter. So Im stuck :(
Any suggestions? thanks a lot!

Following your methodology for defining row index, you can use:
Iterator<Map<String, String>> iter = allFieldValues.iterator();
Map<String, String> row;
for (int i = 0; i <= rowIndex; i++) {
row = iter.next();
}
String col;
Iterator<String> iter2 = row.values().iterator();
for (int i = 0; i <= colIndex; i++) {
col = iter2.next();
}

Related

Enumerate the unordered pairs (2-combinations) of a set

I'd like to iterate through an ArrayList representing a set of Persons and compare the content of each Person with each other Person. The content are full of Hasmaps in this form. I need to compare the Value of the matching Key (Key is unique) and get the difference of the Integer. This should iterate through all the Hashmaps and for all the Persons in the Arraylist. But I shouldn't compare p.e. Person A with Person C and then Person C again with Person A.
How can I code it?
I'm struggling for the last 3 hours.
public Integer comparison(){
ArrayList<HashMap> personList = new ArrayList<>();
for(int i = 0; i < personList.size(); i++){
HashMap<String, Integer> persons = new HashMap<>();
for(int j = i+1; j<persons.size(); j++){
// sum up the differences
}
difference+=difference;
}
return difference;
}
This topic in mathematics uses what are called Combinations wherein you need to find the set of all k-combinations of a set (persons A, B, and C). In this case it is simple to get all the combinations, because you know it is always only required to choose two elements; that is, k=2. See my outer loop and inner loop below for an easy way of achieving this:
for(int a=0; a < personList.size()-1 /* stop before last */; a++) {
for(int b=a+1 /* start after first */; b < personList.size(); b++) {
int sumDiff = 0;
System.out.print("person"+(char)('A'+a)+" compared with person"+(char)('A'+b)+" = ");
Set<String> keys = personList.get(a).keySet();
keys.retainAll(personList.get(b).keySet()); // keys in both only
for(String key : keys) {
sumDiff += Math.abs(personList.get(a).get(key)-personList.get(b).get(key));
}
System.out.println(sumDiff);
}
}
Output:
personA compared with personB = 11
personA compared with personC = 8
personB compared with personC = 9
First of all, it is very unclear as to what you want to do. I am assuming that you have been given the personList and you pass it to the function you are writing. If you want the result as a list of individual comments you need to add them to a list and return a List instead of an Integer.
The following code for your example should return a List which contains the values {11,8,9}. If you want the sum of these values like 11+8+9 then instead of adding each difference to a list add it to a variable initialized to 0 and declared outside the 1st for loop.
public List<Integer> comparison(ArrayList<HashMap> personList){
List<Integer> result = new ArrayList<Integer>();
//int res = 0;
for(int i = 0; i < personList.size(); i++){
for(int j=i+1; j< personList.size(); j++){
int difference = 0
for(Map.Entry<String, Object> entry : personList.get(i).entrySet()){
String key = entry.getKey();
int val = entry.getValue();
difference += Math.abs(personList.get(j).get(key) - val);
}
}
//res += difference
result.add(difference);
}
//return res;
return result;
}

The easiest way to convert arrayList to object[][]

I am receiving my data from the database in the type of
Map<String,ArrayList<String>
So, the columns' names are the keys, and the columns values are stored in the
ArrayList<String>
I need to convert these hash to Object [][] data; for presenting data.
I know, how simple solutions like loops work.
But i would like to know what is the shortest solution to convert
ArrayList<String> to Object[][] data
I am using java 8.
Let's say, at the beginning i have
Map<String, ArrayList<String>> res
Point:
I have the data in ArrayList<String> means that, I have access to data vertically, but i in Object [][] it is somehow horizontally.
As i said res is the database table, so Object [][] would be a row, meanwhile the ArrayList<String> is the column
How about this?
Object[][] result = res.entrySet()
.stream()
.map(e -> e.getValue().toArray())
.collect(Collectors.toList())
.toArray(new Object[0][0]);
The resulting array has the dimension: result[col][row]. So when iterating:
for(int col = 0; col < result.length; col++) {
for(int row = 0; y < result[col].length; row++){
result[col][row]; //table cell
}
}
Java 8 provides an efficient solution for converting it to a data object as stated well by #Gerald in the above answer.
However, if you are also interested in doing this in the naive approach then I have implemented the code as follows.
Map<String, ArrayList<String>> map = new HashMap<>();
String[] arr1 = { "I", "am", "good" };
List<String> list = Arrays.asList(arr1);
map.put("Max", new ArrayList<String>(list));
arr1 = new String[]{"I", "am", "always", "excited"};
list = Arrays.asList(arr1);
map.put("Peter", new ArrayList<String>(list));
System.out.println(map);
// OUTPUT: {Max=[I, am, good], Peter=[I, am, always, excited]}
Object[][] data = new Object[map.size()][];
int i = 0;
// iterate the map and store to Object data
for(Map.Entry<String, ArrayList<String>> entry : map.entrySet()) {
data[i] = new Object[entry.getValue().size() + 1]; // number of records from list + (One) map key
data[i][0] = entry.getKey(); // save key at '0'th index
int j = 1; // iterate the ArrayList to save values in the same row.
for(String s : entry.getValue()) {
data[i][j++] = s;
}
i++;
}
// Printing the data object
for(i = 0; i < data.length; i++) {
for(int j = 0; j < data[i].length; j++) {
System.out.print(data[i][j] + " ");
}
System.out.println();
}
// OUTPUT :
//Max I am good
//Peter I am always excited

dynamicaly create arrayList in JAVA

I need to create 50 arraylists but rather than having to initialise them all individually. Is there a way in JAVA that I can do this dynamically??
i.e.
pseudo code:
for int i=1; i<51; i++
List<String> Counti = new ArrayList<String>();
So that in the loop it goes through and create 50 arraylists all called Count1, Count2, Count3 etc up until Count50.
I've tried creating a string and then naming the list by the string but it doesnt seem to recognise that teh name is a variable.
e.g.
for int i=1; i<51; i++
String Name="Count "+i
List<String> Name = new ArrayList<String>();
Instead it just creates a list called "Name"
You can do this with reflection, but this is a pretty bad idea. What you probably want to do is create an arraylist of arraylists.
ArrayList<ArrayList<String>> listOfLists = new ArrayList<ArrayList<String>>();
for (int i = 0; i < 50; i++)
listOfLists.add(new ArrayList<String>());
You should store them in a List and not create 50 variables
List<List<String>> lists = new ArrayList<ArrayList<String>>();
for (int i = 0; i < 50; i++)
{
lists.add(new ArrayList<String>());
}
You need a List of ArrayList.
List<List<String>> lists = new ArrayList<>();
for (int i = 0; i < 50; i++){
lists.add(new ArrayList<String>());
}
one another possible solution is to use a HashMap like this to name the ArrayLists:
Map<String, ArrayList<String>> mAllArrayListsByName = new HashMap<String, ArrayList<String>>();
for (int i = 0 ; i < 50 ; i++){
mAllArrayListsByName.put("List"+String.valueOf(i), new ArrayList<String>());
}
ArrayList<String> lMyArrayList = mAllArrayListsByName.get("List0"); // get List 0

save get values using arrayList java

In my example, I try to get val(0) and val(1) each time.
After for loop I need to save my values to use them for other calculations:
String[] columns = { "col1" , "col2" };
String[] y = { "TEST", "BUG" ,"ENH" };
List<int[]> values = new ArrayList<int[]>();
for (int j = 0; j < y.length; j++) {
// do some actions
for(int[] v : values) {
//v is the array for one iteration, use it like this:
int col1 = v[0];
int col2 = v[1];
values .add(v);
}
}
System.out.prinln(values) =>gives : []
Out of for loop, my values are raised, how do can I do to get my values after for?
Thanks
I don't understand the question either, but, here's my best guess at interpreting what the question is trying to do:
String[] columns = {"col1" , "col2"};
String[] y = { "TEST", "BUG" ,"ENH"};
int[][] values = new int[y.length][columns.length]; // 2D array
for (int j = 0; j < y.length; j++) {
for (k = 0; k < columns.length; k++) {
values[j][k] = table.getVal(j, columns[k]);
}
}
for (int value : values) {
// do something with value
}
Without knowing the structure of 'table', your data in the int array 'values' should be readily accessible via a for loop:
for (int v: value) {
//use 'v' here
}
or directly:
values[0];
values[1];
...etc
However, it might simply be a language barrier here preventing us from understanding the true problem.
If you want to get the values of all iterations after the loop, you first have to provide a fitting data structure. An easy way might be to use a 2-dimensional array:
int[][] values = new int[y.length][columns.length];
However, I'd recommend using a collection instead (assuming the original values has to be an array):
List<int[]> values = new ArrayList<int[]>();
Then fill that in your loop, either using array index y or just adding a new array in each iteration.
After the loop you can then iterate over the result, like this:
for(int[] v : values) {
//v is the array for one iteration, use it like this:
int col1 = v[0];
int col2 = v[1];
//or like this
for(int value : v) {
//value is the value of one column in one iteration
}
}
UPDATE:
In your updated code you're not putting anything into the list.
Note that you still have to create an array per iteration, get the values from your source (IIRC it was named table) and put them into the array, then add the array to the list using values.add(...).
Also note that the loop I added above is meant to read the values later, it doesn't show you how to fill the list in the first place.

Objects in ArrayList not retaining their type using generics

I have a two-dimensional ArrayList to store Block objects to use later. However, it won't let me call Block methods on the objects when I get them by their index in the list. Here is the code where I initialize the list:
ArrayList<ArrayList> col = new ArrayList<ArrayList>();
for(int column = 0; column < SIZE; column++) {
// Add a row of block objects
col.add(new ArrayList<Block>());
// Populate the row
for(int row = 0; row < SIZE; row++) {
col.get(column).add(new Block());
grid.add((Block) col.get(column).get(row));
}
}
The problem seems to be that when I go to add the block to the grid (a JPanel), it won't compile unless I cast the object back to a Block. In other words, grid.add(col.get(column).get(row))
won't work. Any ideas why this might be happening?
You need it to be
ArrayList<ArrayList<Block>> col = new ArrayList<ArrayList<Block>>();
When you have just ArrayList<ArrayList> the get's would look like this
ArrayList<ArrayList> col = new ArrayList<ArrayList>();
ArrayList list = col.get(i);
Object obj = list.get(j);
Since list is an ArrayList with no type it will always return an Object.
If you have it as ArrayList<ArrayList<Block>> it would look like
ArrayList<ArrayList<Block>> col = new ArrayList<ArrayList<Block>>();
ArrayList<Block> list = col.get(i);
Block obj = list.get(j);

Categories