I need to convert an 2D array to list and remove the duplicates and print the values.
By using the below code, I'm unable to print the 2D array
When I tried to print it, it is printing the index value.
Even I tried using Iterator,
int array2D [][] = {{111,555,111,78,98},{87,54,53}};
ArrayList<Integer> numberList = new ArrayList<Integer>();
for(int i=0;i<array2D.length;i++)
{
for(int j=0;j<array2D[i].length;j++)
{
numberList.add(i, j);
}
}
System.out.println(numberList);
Iterator iter = numberList.iterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
Still it is not working.
When I tried to print it, it printing the index value.
It is printing the index value because you added the indexes instead of actual value. You should add the actual value of an array by index i
and j
like:
numberList.add(array2D[i][j]);
If you want to remove duplicates you could use Set
instead of ArrayList
:
Set<Integer> numberList = new LinkedHashSet<>();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.