Add null values to 2d List with Generics - java

I'm trying to create a two-dimensional List of a table that holds a single type of object with predefined rows and columns and initialize all cels as null, but it wont pass the test below why?
public class Tab<E> {
public Tab(int rows, int columns) {
List<List<E>> listOfLists = new ArrayList();
for (int i = 0; i < rows; ++i) {
List<E> list = new ArrayList();
listOfLists.add(list);
for (int j = 0; j < columns; ++j) {
list.add((E) null);
}
}
}
}
Test:
Tab<Integer> tab;
tab = new Tab<>(2, 3);
boolean allNull = tab.toList().stream().allMatch(Objects::isNull);

Constructors can not return any value. if you want to have a list first of all put your code in a method and after that by returning the two dimensional array and streaming on it you would get the correct answer
public List<List<E>> myarrays(int rows, int columns){
List<List<E>> listOfLists = new ArrayList();
for (int i = 0; i < rows; ++i) {
List<E> list = new ArrayList();
listOfLists.add(list);
for (int j = 0; j < columns; ++j) {
list.add((E) null);
}
}
return listOfLists;
}
and after that you can use this:
boolean allNull = tab.myarrays(2,3).stream().filter(a ->a==null).allMatch(Objects::isNull);

The purpose of a constructor is to create an instance of a class and [usually] to also initialize the class fields. I think you need to make listOfLists a class field.
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class Tab<E> {
private List<List<E>> listOfLists;
public Tab(int rows, int columns) {
listOfLists = new ArrayList<>(rows);
for (int i = 0; i < rows; ++i) {
List<E> list = new ArrayList<>(columns);
listOfLists.add(list);
for (int j = 0; j < columns; ++j) {
list.add((E) null);
}
}
}
public static void main(String[] args) {
Tab<Integer> tab = new Tab<>(2, 3);
boolean allNull = tab.listOfLists.stream() // returns a stream where the type of each element is 'List<E>'
.flatMap(lst -> lst.stream()) // returns a stream where the type of every element is 'E'
.allMatch(Objects::isNull);
System.out.println(allNull);
}
}

Related

How to convert ArrayList<Double> to 2D array? I'll want a matrix

I have an ArrayList like this:
[2.0, 3.0, 5.0, ...., 9.0] // has 30 value inside
I got that output from this code
ArrayList<Double> data = new ArrayList<Double>();
for (Document matrix : matrices) {
Double column1 = matrix.getDouble("column1");
data.add(column1);
Double column2 = matrix.getDouble("column2");
data.add(column2);
Double column3 = matrix.getDouble("column3");
data.add(column3);
Double column4 = matrix.getDouble("column4");
data.add(column4);
Double column5 = matrix.getDouble("column5");
data.add(column5);
}
System.out.println("Current array list is:"+data);
So, can I convert the array list = data[30] to 2d array = data[6][5] ?
Maybe like this output
data[6][5] :
2.0 3.0 5.0 ... ...
.
.
.
.
... ... ... ... 9.0
Or I have to make 6 different initiation ArrayList to get matrix?
I wrote this a while ago for matrixs. It handles the difference forms (list, array, 2d arrays, etc). Should be what you need
package com.bossanova.hitl.utils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
*
* #author Dan
*
* #see This has moved to commons
*/
#Deprecated
public class ArrayUtils {
private static Gson gson;
static{
gson = new Gson();
}
public static <T extends Number> T[][] convertListTo2DArray(List<T> elements, Class<T> numberClass, int rows, int cols) {
if (rows * cols < elements.size()) {
throw new IndexOutOfBoundsException("Theres not going to be enough room in the array for all the data");
}
#SuppressWarnings("unchecked")
T[][] array = (T[][]) Array.newInstance(numberClass, rows, cols);
int index = 0;
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
array[row][col] = elements.get(index);
index++;
}
}
return array;
}
public static double[][] convertDoubleListTo2DPrimativeArray(List<Double> elements, int rows, int cols) {
Double[][] twoDArray = convertListTo2DArray(elements, Double.class, rows, cols);
double[][] retVal = new double[rows][cols];
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
retVal[row][col] = twoDArray[row][col];
}
}
return retVal;
}
public static List<Double> convert2DArrayToList(double[][] data) {
int rows = data.length;
int cols = data[0].length;
List<Double> retVal = new ArrayList<>();
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
retVal.add(data[row][col]);
}
}
return retVal;
}
public static double[][] deepCopy(double[][] original) {
final double[][] result = new double[original.length][];
for (int i = 0; i < original.length; i++) {
result[i] = Arrays.copyOf(original[i], original[i].length);
}
return result;
}
public static double[][] convertJsonDoubleArrayTo2DArray(String json, int rows,int cols){
return convertDoubleListTo2DPrimativeArray(convertJsonDoubleArrayToDoubleList(json), rows, cols);
}
public static List<Double> convertJsonDoubleArrayToDoubleList(String json){
List<Double> doubleList = gson.fromJson(json, new TypeToken<List<Double>>(){}.getType());
return doubleList;
}
}
Just do some basic arithmetic to lookup the co-ordinates you want.
static Double getXY(List<Double> list, int x, int y, int numberOfColumns) {
return list.get(y * numberOfColumns + x);
}
Maybe the other answers are better but this solved my problem:
data.toArray();
double[][] matrix2D = new double[ribet.size()/5][5];
int k=0;
for (int i=0; i<data.size()/5; i++) {
for (int j=0; j<5; j++) {
matrix2D[i][k%5] = data.get(k);
k = k+1;
}
}

Matrix with ArrayList

I got this class :
import java.util.*;
public class MatrixArrayList extends AbstractMatrix {
private ArrayList<ArrayList<Integer>> values;
public MatrixArrayList(int nbl, int nbc) {
super(nbl, nbc);
values=new ArrayList<ArrayList<Integer>>();
}
#Override
public int getValue(int x, int y) {
return values.get(x).get(y) ;
}
#Override
public void setValue(int x, int y, int value) {
values.get(x).set(y, value);
}
}
and I got
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
I want to make a matrix with an ArrayList
i have w problem with this :
valeurs.get(x).set(y, valeur);
It's not clear from your code which call causes the exception, however it is clear that you are not initializing your inner array-list, nor are you adding any objects to it.
When you initialize it in the constructor:
values=new ArrayList<ArrayList<Integer>>();
What you're basically doing is instantiating the values object to be an ArrayList of size 0 (no items have been added to it yet).
Then, if say, you're doing setValue at index 0, you get the exception because when you do get(x), you're basically doing get(0) on a collection of size 0 - there is nothing to get, you exceed the bounds of the your array.
What you might want to do is initialize all arrays in the constructor:
public MatrixArrayList(int nbl, int nbc) {
super(nbl, nbc);
values=new ArrayList<ArrayList<Integer>>(nbl);
for (int i = 0; i < nbl; i++) {
values.add(new ArrayList<Integer>(nbc));
}
}
And then you can access them without a problem in getValue or setValue (you'll get this exception if you actually do exceed the bounds or if you haven't set any value at the specific index yet. See comment below:).
Notice, though, that since you're using the ArrayList object, rather than a primitive int[] array, you still don't have values inside your array. Simply doing new ArrayList<Integer>() or even new ArrayList<Integer>(num) still leaves you with a list of size 0. If you want to cover all your bases, you might want to either initailize your ArrayList, or perform bounds checks before each get you make in either getValue or setValue.
new ArrayList<ArrayList<Integer>>() creates an empty list. To fill that list with values, you need to call add().
Assuming you want to fill matrix with nbl lists of nbc null values:
this.values = new ArrayList<>(nbl);
for (int i = 0; i < nbl; i++) {
ArrayList<Integer> row = new ArrayList<>(nbc);
for (int j = 0; j < nbc; j++)
row.add(null);
this.values.add(row);
}
You could also fill it with 0 values if you want.
Of course, if the matrix cannot change size, it would likely be much better to create a simple array version, instead of the ArrayList version you're trying to create.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class Shell {
static List<ArrayList<ArrayList<Double>>> read(String filename) {
ArrayList<ArrayList<Double>> A = new ArrayList<ArrayList<Double>>();
ArrayList<ArrayList<Double>> B = new ArrayList<ArrayList<Double>>();
String thisLine;
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
// Begin reading A
while ((thisLine = br.readLine()) != null) {
if (thisLine.trim().equals("")) {
break;
} else {
ArrayList<Double> line = new ArrayList<Double>();
String[] lineArray = thisLine.split("\t");
for (String number : lineArray) {
line.add((double) Integer.parseInt(number));
}
A.add(line);
}
}
// Begin reading B
while ((thisLine = br.readLine()) != null) {
ArrayList<Double> line = new ArrayList<Double>();
String[] lineArray = thisLine.split("\t");
for (String number : lineArray) {
line.add((double) Integer.parseInt(number));
}
B.add(line);
}
} catch (IOException e) {
System.err.println("Error: " + e);
}
List<ArrayList<ArrayList<Double>>> res = new LinkedList<ArrayList<ArrayList<Double>>>();
res.add(A);
res.add(B);
return res;
}
static int[][] ijkAlgorithm(ArrayList<ArrayList<Integer>> A,
ArrayList<ArrayList<Integer>> B) {
int n = A.size();
// initialise C
int[][] C = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
C[i][j] += A.get(i).get(k) * B.get(k).get(j);
}
}
}
return C;
}
static void printMatrix(Matrix matrix, int n) {
for (int i = 0; i < n; i++) {
StringBuilder sb = new StringBuilder(matrix.length);
for (int j = 0; j < n; j++) {
if (j != 0) {
sb.append("\t");
}
String formattedString = String.format("%.0f", matrix.get(i, j))
sb.append(formattedString);
}
System.out.println(sb.toString());
}
}
public static void main(String[] args) {
String filename;
if (args.length < 2) {
filename = "2000.in";
} else {
filename = args[1];
}
List<ArrayList<ArrayList<Double>>> matrices = read(filename);
ArrayList<ArrayList<Double>> A = matrices.get(0);
ArrayList<ArrayList<Double>> B = matrices.get(1);
int n = A.size();
double[][] Aarray = new double[n][n];
double[][] Barray = new double[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
Aarray[i][j] = A.get(i).get(j);
Barray[i][j] = B.get(i).get(j);
}
}
Matrix AM = new Matrix(Aarray);
Matrix BM = new Matrix(Aarray);
Matrix CM = AM.times(BM);
printMatrix(CM, n);
}
}
input file that have matrices you want to do this operation
Hope this code helps happy coding.

TestNG DataProvider - How to produce all permutations in a List

Supposed I have a list of string, I want a DataProvider to produce permutation of 2 of that list to use as 2 parameter in one of the test function. What I have so far is:
#DataProvider(name = "Permutation")
public static Object[][] permutations() {
List <String> permutations = getPermutationList();
Object[][] dataList = new Object[permutations.size()][permutations.size()];
for (int i = 0; i < permutations.size(); i++) {
dataList[i] = new Object[permutations.size()];
for (int j = 0; j < permutations.size(); j++) {
dataList[i][j] = permutations.get(i);
}
}
return dataList;
}
My DataProvider doesn't work as expected, every row is just null.
Any hint please? Thank you
The getPermutationList is the issue with your code. Ensure it's returning the data you are expecting. Below is the same code as above, only with a hardcoded array being initialized. When it runs, there is data in the dataList object.
public static Object[][] permutations() {
List <String> permutations = new ArrayList<String>(Arrays.asList("foo", "bar"));
Object[][] dataList = new Object[permutations.size()][permutations.size()];
for (int i = 0; i < permutations.size(); i++) {
dataList[i] = new Object[permutations.size()];
for (int j = 0; j < permutations.size(); j++) {
dataList[i][j] = permutations.get(i);
}
}
return dataList;
}

Problems with returning ArrayList

I added Strings "Hello", "Cat", "Dog" into the arraylist called values passed it to the method doubleIt() which should return a list of everything doubled, i.e.
"Hello", "Hello", "Cat", "Cat", "Dog", "Dog"
But all Im getting is []. What could I do wrong here ?
import java.util.*;
public class Addition
{
public static void main(String [] args)
{
List<String> values = new ArrayList<String>();
values.add("Hello");
values.add("Cat");
values.add("Dog");
values = doubleIt(values);
System.out.println(values);
}
public static List<String> doubleIt(List<String> values)
{
List<String> temp = new ArrayList<>();
for(int i = 0; i < temp.size(); i++)
{
temp.add(values.get(i*2));
}
return temp;
}
}
Your first mistake is here...
for(int i = 0; i < temp.size(); i++)
temp.size() will be 0 when it's called the first time, you really should be using a values, but this will cause an IndexOutOfBoundsException
So you could use something like...
for (int i = 0; i < values.size(); i++) {
temp.add(values.get(i));
temp.add(values.get(i));
}
instead
First change your for loop condition from
for(int i = 0; i < temp.size(); i++)
to
for(int i = 0; i < values.size(); i++)
and then add values 2 times each.
Your for loop in doubleIt() was looping up to the wrong list size. And you were trying to multiply a string by 2, instead of adding it twice.
public static List<String> doubleIt(List<String> values)
{
List<String> temp = new ArrayList<>();
for(int i = 0; i < values.size(); i++) // <-- you needed to loop up to the size of the values list, not the temp list
{
temp.add(values.get(i));
temp.add(values.get(i));
}
return temp;
}

Adding Integers to ArrayList<Integer>

I have an ArrayList of LinkedLists (an array of linked lists). The LinkedLists contains integers (Integer).
private List<LinkedList> buckets;
buckets = new ArrayList<LinkedList>();
for (int i = 0; i < 10; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
buckets.add(temp);
}
I later want to remove the items from the linked list (in the order they were added) and add them to an array list. When I try this:
ArrayList<Integer> sorted = new ArrayList<Integer>(unsorted.size());
for (int i = 0; i < buckets.size(); i++) {
for (int j = 0; j < buckets.get(i).size(); j++) {
sorted.add(buckets.get(j).removeLast());
// sorted.add((Integer)buckets.get(j).removeLast());
}
}
I get an error saying:
add(java.lang.Integer) in ArrayList cannot be applied to (java.lang.Object)
But when I cast it to an Integer (the commented out line), the array is full of null values. Anyone see what I am doing wrong?
Here is where I am adding items to bucket:
for (int i = 0; i < unsorted.size(); i++) {
int digit = (unsorted.get(i) / position) % 10;
buckets.get(digit).add(unsorted.get(i));
}
Note that sorted is an ArrayList<Integer>. When I trace it in debug mode, I can see that the LinkedLists have Integer objects with the correct values.
Screenshot of buckets contents:
Working Example:
class Ideone {
private static List<LinkedList<Integer>> buckets;
public static void main (String[] args) throws Exception {
ArrayList<Integer> arr = new ArrayList<Integer>();
arr.add(6);
arr.add(8);
arr.add(1);
arr.add(3);
arr.add(9);
System.out.println(arr);
arr = sort(arr);
System.out.println(arr);
}
public static ArrayList<Integer> sort(ArrayList<Integer> unsorted) {
buckets = new ArrayList<LinkedList<Integer>>();
for (int i = 0; i < 10; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
buckets.add(temp);
}
ArrayList<Integer> sorted = new ArrayList<Integer>(unsorted.size());
for (int i = 0; i < unsorted.size(); i++) {
int digit = unsorted.get(i) % 10;
buckets.get(digit).add(unsorted.get(i));
}
for (int i = 0; i < buckets.size(); i++) {
for (int j = 0; j < buckets.get(i).size(); j++) {
sorted.add(buckets.get(j).poll());
// sorted.add((Integer)buckets.get(j).removeLast());
}
}
return sorted;
}
}
You are using the raw form of LinkedList here:
private List<LinkedList> buckets;
Because of this, removeLast will return Object, not Integer. Try
private List<LinkedList<Integer>> buckets;
and
buckets = new ArrayList<LinkedList<Integer>>();
Casting the return of removeLast to Integer was the pre-generics way of getting this to work. However, you never inserted any items into each LinkedList, so removeLast returns null. If you want something returned, first insert something into each LinkedList that gets inserted into buckets.
Casting to Integer would still work, but supplying Integer as the type argument to LinkedList is preferred, especially since you are using generics by supplying LinkedList as the type parameter to List already.
In your nested loop,
for (int i = 0; i < buckets.size(); i++) {
for (int j = 0; j < buckets.get(i).size(); j++) {
// ***** here *****
sorted.add(buckets.get(j).poll());
}
}
You look to be polling the wrong List.
Try changing
sorted.add(buckets.get(j).poll());
to:
sorted.add(buckets.get(i).poll());
Perhaps a cleaner more intuitive way to code this would be something like:
for (int i = 0; i < buckets.size(); i++) {
LinkedList<Integer> innerList = buckets.get(i);
for (int j = 0; j < innerList.size(); j++) {
sorted.add(innerList.poll());
}
}
Although this may not work if the innerList has multiple items. Why not instead remove items safely with an iterator?
for (int i = 0; i < buckets.size(); i++) {
LinkedList<Integer> innerList = buckets.get(i);
for (Iterator<Integer> iterator = innerList.iterator(); iterator.hasNext();) {
sorted.add(iterator.next());
iterator.remove(); // this guy is optional
}
}
Either that or simply use get(j)
for (int i = 0; i < buckets.size(); i++) {
LinkedList<Integer> innerList = buckets.get(i);
for (int j = 0; j < innerList.size(); j++) {
sorted.add(innerList.get(j));
}
}
Although this isn't efficient use of a LinkedList
The item that you inserted into the ArrayList "sorted" is the item you took from the link list LinkedList.
But you never actually add any item to it. You simply just created a LinkedList and added it to your bucket list.
You need to add something into the temp list.
for (int i = 0; i < 10; i++) {
LinkedList<Integer> temp = new LinkedList<Integer>();
// Add something to the temp LinkedList
buckets.add(temp);
}

Categories