Remove row from multidimensional array - java

I have this multidimensional array:
String[][] qArray = new String[][] {
{"question", "answerOption1", "answerOption2", "answerOption3", "answerOption4"}
{"question", "answerOption1", "answerOption2", "answerOption3", "answerOption4"}
}
I assign the question text to a TextView and the andswerOptions to text on Buttons. The order is randomly selected, so because the question isnt supposed to be asked twice, i need to remove the question just asked. What i have read i need to delete this array and create a new one, but i'm not quite sure how this is done. I'm not sure how the for syntax is in Java, but here is my guess:
Assuming the question asked is held in TextView tv
String[][] newArray = new String[qArray.length-1][5] {
For rows in qArray do newArray.addRow
if (qArray[0..qArray.length][0] != tv.getText());
qArray = newArray
And then redoing the methods again untill there are no more questions left.

If you are just looking for a for loop implementation. why not use something like this
String[][] newArray = new String[qArray.length][5];
for(int i=0; i<=qArray.length-1; i++){
for(int j=0; j<5; j++){
newArray[i][j] = qArray[i][j];
}
}

public static void main(String[] args){
String[][] qArray = new String[][]{
{"question", "answerOption1", "answerOption2", "answerOption3", "answerOption4"},
{"question5", "answerOption6", "answerOption7", "answerOption8", "answerOption9"}
};
List<String[]> list = new ArrayList<String[]>(Arrays.asList(qArray));
list.remove(1);//row that needs to be deteted
String[][] qArray1 = list.toArray(new String[][]{});
for (String[] arr : qArray1) {
System.out.println(Arrays.toString(arr));
}
}

A queue is meant for this.
public static void main(String[] args)
{
String[][] qArray = new String[][]
{
{"question", "answerOption1", "answerOption2", "answerOption3", "answerOption4"},
{"question5", "answerOption6", "answerOption7", "answerOption8", "answerOption9"}
};
Queue<String[]> list = new LinkedList<String[]>(Arrays.asList(qArray));
for (String[] theArr = list.poll() ; theArr!=null ; theArr = list.poll())
{
for (String theStr : theArr)
{
System.out.print(theStr + " ");
}
System.out.print("\n");
}
}

Related

Java fill 2d array with 1d arrays

Whats the nicest way to fill up following array:
From main:
String[][] data = new String[x][3];
for(int a = 0; a < x; a++){
data[a] = someFunction();
}
Function I am using..:
public String[] someFunction(){
String[] out = new String[3];
return out;
}
Is it possible to do something like this? Or do I have to fill it with for-loop?
With this code im getting error "non-static method someFunction() cannot be refferenced from static content ---"(netbeans) on line data[a] = someFunction();
You have to specify how many rows your array contains.
String[][] data = new String[n][];
for(int i = 0; i < data.length; i++){
data[i] = someFunction();
}
Note that someFunction can return arrays of varying lengths.
Of course, your someFunction returns an array of null references, so you still have to initialize the Strings of that array in some loop.
I just noticed the error you got. Change your someFunction to be static.
Change your someFunction() by adding "static".
You also should consider using an ArrayList for such tasks, those are dynamic and desinged for your purpose (I guess).
public static void main(String[] args){
int x = 3;
String[][] data = new String[x][3];
for(int a = 0; a < x; a++){
data[a] = someFunction();
}
}
public static String[] someFunction(){
String[] out = new String[3];
return out;
}
Greetings Tim

Dynamically creating ArrayList inside a loop

How do we create arraylist dynamically inside a loop?
something like -
for(i=0;i<4;i++)
{
List<Integer> arr(i) = new ArrayList<>();
}
It sounds like what you actually want is a list of lists:
List<List<Integer>> lists = new ArrayList<List<Integer>>();
for (int i = 0; i < 4; i++) {
List<Integer> list = new ArrayList<>();
lists.add(list);
// Use the list further...
}
// Now you can use lists.get(0) etc to get at each list
EDIT: Array example removed, as of course arrays of generic types are broken in Java :(
Creating a list of Arraylist:
import java.io.*;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
int i=0;
Scanner obj=new Scanner(System.in);
List<List<Integer>> lists = new ArrayList<List<Integer>>();
System.out.println("Enter the number of lists");
int n=obj.nextInt();
while (i<n) {
List<Integer> list = new ArrayList<Integer>();
System.out.println("Enter the number of integers you want to enter in an ArrayList");
int d=obj.nextInt();
for(int j=0;j<d;j++){
list.add(obj.nextInt());
}
lists.add(list);
System.out.println("List "+i+ "is created");
System.out.println(lists.get(i));
System.out.println("");
i++;
} //end of while
} //end of main
} //end of class
Maybe you want something like this. This will be creating a number of "List" as much as you want. In this case, I am creating two Lists:
import java.util.LinkedList;
import java.util.List;
public class NumberOfList {
public static void main (String [] args){
List<Integer> list[];
list = new LinkedList[2];
for(int x=0; x<2; x++){
list[x]= new LinkedList();
}
}
}
You can try this.
List<List<Integer>> dataList = new ArrayList<List<Integer>>();
for(int i = 1; i <= 4; i++)
{
List<Integer> tempList = new ArrayList<Integer>();
dataList.add(tempList);
}
For adding data
for(int i = 1; i <= 4; i++)
{
int value = 5+i;
dataList.get(i - 1).add(value);
}
Create an ArrayList having an ArrayList as it's elements.
ArrayList<ArrayList<Integer>> mainArrayList =
new ArrayList<ArrayList<Integer>>();
you can add elements into mainArrayList by:
ArrayList<Integer> subArrayList;
for(int i=0;i<4;i++) {
subArrayList = new ArrayList<Integer>();
subArrayList.add(1); // I'm adding a random value to subArrayList
mainArrayList.add(subArrayList);
}
Now, the mainArrayList will have the 4 arrayLists that we added and we can access
each element(which are ArrayLists) using for loop.
List<List<Integer>> dataList = new ArrayList<List<Integer>>();
for(i=0;i<4;i++)
{
List<Integer> arr = new ArrayList<>();
dataList .add(arr );
}
This might help you. If not, please clarify the scenario.
I am not sure what you mean, maybe this?
List<Integer> arr = new ArrayList<Integer>();
for(i=0;i<4;i++)
{
arr.add(i);
}

find duplicate words in java array and return array with unique duplicate words - use method

I am new to java, and am confused with the problem.
This is what I came up so far.
I am still working on it, if I come up with any progress, I'll post it here.
public class charArray {
public static void main(String[] args) {
String[] strArray = new String[] {"apple", "ball", "cat", "apple", "ball", "apple"};
//output should be ["apple", "ball"]
checkDuplicate(strArray);
}
public static String[] checkDuplicate(String[] strArray){
String[] newArray = new String[]{};
for(int i = 0; i < strArray.length; i++){
for(int j = 0; j < i; j++){
if (strArray[i].equals(srtArray[j])){
newArray = strArray[i];
}
}
}
return newArray[];
}
}
New progress:
Ok, my mediocre head has gone this far: (and the solution works)
It prints out the unique array of Duplicate elements.
But now I need to implement the same code, by calling a method.
Any help is appreciated.
import java.util.*;
public class setChar {
public static void main(String[] args) {
String[] strArray = new String[] {"apple", "ball", "cat", "apple", "ball", "apple"};
Set set = new HashSet();
Set uniqueSet = new HashSet();
for(int i = 0; i < strArray.length ; i++ ){
boolean b = set.add(strArray[i]);
if(b == false){
uniqueSet.add(strArray[i]);
}
}
Iterator it = uniqueSet.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
}
}
The output is:
ball
apple
Finally implemented with method, with proper return type.
Please let me know, if this can be further optimized.
Thank all for you suggestions. Here is the working code:
public class retUnique {
public static void main(String[] args) {
String[] strArray = new String[] {"apple", "ball", "cat", "apple", "ball", "apple"};
System.out.println(printUnique(strArray));
}
public static Set<String> printUnique(String[] strArray){
Set<String> set = new HashSet<String>();
Set<String> uniqueSet = new HashSet<String>();
for(int i = 0; i < strArray.length ; i++ ){
boolean b = set.add(strArray[i]);
if(b == false){
uniqueSet.add(strArray[i]);
}
}
return(uniqueSet);
}
}
One easy option is to use a Set like container instead of an array. It will automatically ensure that only unique values are present.
You can look at examples of TreeSet and HashSet.
Something like this should work I believe. Been a while since I coded in Java so if anyone wants to make edits, please do.
public String[] returnDups(String[] strArray) {
Set<String> set = new HashSet<String>(strArray);
return set.toArray(new String[0]);
}
But what everyone has been suggesting is the correct idea. Sets make it really easy to remove duplicates so you should utilize them. Let's not reinvent the wheel.
To detect dupplicates, if that is your question, add all elememts of the array to a Set, if set.add() returns false, then it is a dupplicate, so you can add this elemen to your result list of dupplictes.
Or if your question is meaning to return the values without duplicates, then you can retirnthe set, or convert the set to list before returning.

java- how to convert a ArrayList<ArrayList<String>> into String[]][]

I want to store some data in an ArrayList<ArrayList<String>> variable into a csv file.
For this purpose, I zeroed in on Ostermiller Utilities- which include a CSV Writer as well.
The problem is, the csvwrite functionality requires a String, String[] or a String[][] variable.
I wont know beforehand the number of rows/columns in my ArrayList of arraylists-- so how do I use the above (cswrite) functionality? Dont I have to declare a fixed size for a String[]][] variable?
A String[][] is nothing more than an array of arrays. For example, this makes a 'triangular matrix' using a 2d array. It doesn't have to be a square (although CSV probably should be square, it doesn't have to be).
String[][] matrix = new String[][5];
matrix[0] = new String[1];
matrix[1] = new String[2];
matrix[2] = new String[3];
matrix[3] = new String[4];
matrix[4] = new String[5];
So for your purposes
String[][] toMatrix(ArrayList<ArrayList<String>> listOFLists) {
String[][] matrix = new String[][listOfLists.size()];
for(int i = 0; i < matrix.length; i++) {
matrix[i]= listOfLists.get(i).toArray();
}
return matrix;
}
Just keep in mind that in this case, it's in matrix[col][row], not matrix[row][col]. You may need to transpose this result, depending on the needs of your library.
Tested and working:
String[][] arrayOfArraysOfString = new String[arrayListOfArrayListsOfStrings.size()][];
for (int index = 0; index < arrayListOfArrayListsOfStrings.size(); index++) {
ArrayList<String> arrayListOfString = arrayListOfArrayListsOfStrings.get(index);
if (arrayListOfString != null) {
arrayOfArraysOfString[index] = arrayListOfString.toArray(new String[arrayListOfString.size()]);
}
}
Here is an Example of how to convert your multidimesional ArrayList into a multidimensional String Array.
package stuff;
import java.util.ArrayList;
public class ArrayTest {
public static void main(String[] args) throws Exception {
ArrayList<ArrayList<String>> multidimesionalArrayList = createArrayListContent();
String[][] multidimensionalStringArray = new String[multidimesionalArrayList.size()][];
int index = 0;
for (ArrayList<String> strings : multidimesionalArrayList) {
multidimensionalStringArray[index] = strings.toArray(new String[]{});
index++;
}
System.out.println(multidimensionalStringArray);
}
private static ArrayList<ArrayList<String>> createArrayListContent() throws Exception {
ArrayList<ArrayList<String>> result = new ArrayList<ArrayList<String>>();
result.add(createArrayList());
result.add(createArrayList());
result.add(createArrayList());
result.add(createArrayList());
result.add(createArrayList());
return result;
}
private static ArrayList<String> createArrayList() throws Exception {
ArrayList<String> list = new ArrayList<String>();
list.add(String.valueOf(System.currentTimeMillis()));
Thread.sleep(10);
list.add(String.valueOf(System.currentTimeMillis()));
Thread.sleep(10);
list.add(String.valueOf(System.currentTimeMillis()));
Thread.sleep(10);
list.add(String.valueOf(System.currentTimeMillis()));
Thread.sleep(10);
list.add(String.valueOf(System.currentTimeMillis()));
return list;
}
}
You can create an array of arrays (matrix) with one size at first, and then iterate and add the data as you traverse the list of list
String[][] arr = new String[listOfList.size()][];
int i = 0;
for (List<String> row: listOfList) {
arr[i++] = row.toArray(new String[row.size()]);
}

Converting ArrayList to Array in java

I have an ArrayList with values like "abcd#xyz" and "mnop#qrs". I want to convert it into an Array and then split it with # as delimiter and have abcd,mnop in an array and xyz,qrs in another array. I tried the following code:
String dsf[] = new String[al.size()];
for(int i =0;i<al.size();i++){
dsf[i] = al.get(i);
}
But it failed saying "Ljava.lang.String;#57ba57ba"
You don't need to reinvent the wheel, here's the toArray() method:
String []dsf = new String[al.size()];
al.toArray(dsf);
List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[list.size()])
List<String> list=new ArrayList<String>();
list.add("sravan");
list.add("vasu");
list.add("raki");
String names[]=list.toArray(new String[0]);
if you see the last line (new String[0]), you don't have to give the size, there are time when we don't know the length of the list, so to start with giving it as 0 , the constructed array will resize.
import java.util.*;
public class arrayList {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
ArrayList<String > x=new ArrayList<>();
//inserting element
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
x.add(sc.next());
//to show element
System.out.println(x);
//converting arraylist to stringarray
String[]a=x.toArray(new String[x.size()]);
for(String s:a)
System.out.print(s+" ");
}
}
String[] values = new String[arrayList.size()];
for (int i = 0; i < arrayList.size(); i++) {
values[i] = arrayList.get(i).type;
}
What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28%29
Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:
for(String str : dsf){
System.out.println(str);
}
What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you're printing.
package com.v4common.shared.beans.audittrail;
import java.util.ArrayList;
import java.util.List;
public class test1 {
public static void main(String arg[]){
List<String> list = new ArrayList<String>();
list.add("abcd#xyz");
list.add("mnop#qrs");
Object[] s = list.toArray();
String[] s1= new String[list.size()];
String[] s2= new String[list.size()];
for(int i=0;i<s.length;i++){
if(s[i] instanceof String){
String temp = (String)s[i];
if(temp.contains("#")){
String[] tempString = temp.split("#");
for(int j=0;j<tempString.length;j++) {
s1[i] = tempString[0];
s2[i] = tempString[1];
}
}
}
}
System.out.println(s1.length);
System.out.println(s2.length);
System.out.println(s1[0]);
System.out.println(s1[1]);
}
}
Here is the solution for you given scenario -
List<String>ls = new ArrayList<String>();
ls.add("dfsa#FSDfsd");
ls.add("dfsdaor#ooiui");
String[] firstArray = new String[ls.size()];
firstArray =ls.toArray(firstArray);
String[] secondArray = new String[ls.size()];
for(int i=0;i<ls.size();i++){
secondArray[i]=firstArray[i].split("#")[0];
firstArray[i]=firstArray[i].split("#")[1];
}
This is the right answer you want and this solution i have run my self on netbeans
ArrayList a=new ArrayList();
a.add(1);
a.add(3);
a.add(4);
a.add(5);
a.add(8);
a.add(12);
int b[]= new int [6];
Integer m[] = new Integer[a.size()];//***Very important conversion to array*****
m=(Integer[]) a.toArray(m);
for(int i=0;i<a.size();i++)
{
b[i]=m[i];
System.out.println(b[i]);
}
System.out.println(a.size());
This can be done using stream:
List<String> stringList = Arrays.asList("abc#bcd", "mno#pqr");
List<String[]> objects = stringList.stream()
.map(s -> s.split("#"))
.collect(Collectors.toList());
The return value would be arrays of split string.
This avoids converting the arraylist to an array and performing the operation.
NameOfArray.toArray(new String[0])
This will convert ArrayList to Array in java
// A Java program to convert an ArrayList to arr[]
import java.io.*;
import java.util.List;
import java.util.ArrayList;
class Main {
public static void main(String[] args)
{
List<Integer> al = new ArrayList<Integer>();
al.add(10);
al.add(20);
al.add(30);
al.add(40);
Integer[] arr = new Integer[al.size()];
arr = al.toArray(arr);
for (Integer x : arr)
System.out.print(x + " ");
}
}

Categories