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

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

Related

Get permutations of each item available in list

List<String> list = new ArrayList<>();
list.add("MP");
list.add("Maharastra");
list.add("Karnataka");
My requirement is to get all the possible permutation from above list.
Expected Output as list is
[MP:Maharastra, MP:Karnataka, Maharastra:MP, Maharastra:Karnataka, Karnataka:MP, Karnataka:Maharastra]
Currently I added only three items in list but this list can hold any number of items.
You can use a nested loop to pair each element with every other element in the List except itself.
List<String> result = new ArrayList<>();
for(int i = 0; i < list.size(); i++){
for(int j = 0; j < list.size(); j++){
if(i != j){
result.add(list.get(i) + ":" + list.get(j));
}
}
}
System.out.println(result);
With Java 8 streams, it's much simpler:
List<String> result = list.stream().flatMap(s -> list.stream().filter(t -> (Objects.nonNull(t)
&& !t.equalsIgnoreCase(s))).map(t -> s.concat(":").concat(t))).collect(Collectors.toList());

How to store data in a string array using java collection

I have stored data in a List<String[]> and need to store those data into an another String array using a loop. I have created a String array (value) and stored data in there but the issue is first element is getting replaced by second inside the loop and it will show only the last element at the end of the loop.
CSVReader reader = new CSVReader(new FileReader(csvfile));
List<String[]> data = reader.readAll();
String[] values = new String[5];
for (int i = 1; i < 5; i++) {
values = data.get(i);
System.out.println(values[1]); // data is getting replaced here
}
System.out.println(values[1]); // this will show only the last stored value
Lists are 0 indexed so unless you intentionally want to skip the first element then don't start the loop iteration at 1 rather at 0.
Yes, when performing the last println after the loop only data related to the last String[] is shown because at each iteration you're updating values i.e. values = data.get(i); to store the current String[] hence the aforementioned outcome.
You probably want a String[][] as opposed to String[] because each String[] represents a line of the file.
Thus, assuming you only want to get the first five lines from data you can do it as:
String[][] lines = data.subList(0, 5).toArray(String[][]::new);
or for all the lines read:
String[][] lines = reader.readAll().toArray(String[][]::new);
and you can test it with:
System.out.println(Arrays.deepToString(lines));
// generating data
List<String[]> data =
Stream.iterate(0, n -> n + 1)
.limit(10)
.map(i -> new String[]{"a" + i, "b" + i, "c" + i, "d" + i, "e" + i, "f" + i})
.collect(Collectors.toList());
String[][] values = new String[data.size()][];
// copy the data
for (int i = 0; i < data.size(); i++)
{
values[i] = data.get(i).clone();
}
//print the result
Arrays.stream(values).map(Arrays::toString).forEach(System.out::println);
Replace :
for (int i = 1; i < 5; i++) {
values = data.get(i);
System.out.println(values[1]); // data is getting replaced here}
With:
for (int i = 0; i < 5; i++) {
values = data.get(i);
System.out.println(values[1]); // data is getting replaced here}
I think you have a little error inside the for loop. Try this:
CSVReader reader = new CSVReader(new FileReader(csvfile));
List<String[]> data = reader.readAll();
String[] values = new String[5];
for (int i = 1; i < 5; i++) {
values[i] = data.get(i);
System.out.println(values[1]); // data is getting replaced here
}
System.out.println(values[1]); // this will show only the last stored value
I think you are missing the "[i]" at the first line inside the for loop.
Your data variable contains a list of String[] (string arrays). Your for loop is attempting to store them in values which is a single String[].
Depending on what you are trying to do, you can do as the comments suggest and make a 2D String array. However, the fact that you want to remove them from a perfectly good list of String[]'s leads me to believe you probably want them in one big String[].
Below is an example of how to put the first N (in this case 5) words you parse from the csv into the values variable. However, we would be able to give you better guidance if you provided what the ultimate use case of your code snippet is.
// initialize test data
List<String[]> data = new ArrayList<String[]>();
String[] a = {"a1", "a2"};
String[] b = {"b1", "b2"};
String[] c = {"c1", "c2"};
data.add(a);
data.add(b);
data.add(c);
// big N is how many words you want
int N = 5;
// little n tracks how many words have been collected
int n = 0;
String[] values = new String[N];
// loop through csv collect
for (int i = 0; i < data.size(); i++){
String[] cur = data.get(i);
// loop through the strings in each list entry
for (int j = 0; j < cur.length; j++){
// store value and increment counter
values[n] = cur[j];
n++;
// stop if maximum words have been reached
if (n >= N)
break;
}
// stop if maximum words have been reached
if (n >= N)
break;
}
for (int i = 0; i < values.length; i++)
System.out.println(values[i]);

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;
}

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

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

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();
}

Categories