Java 2D string or arraylist? - java

I had a string dataset as follows:
row 1: "abc', "def", "ghi"
row 2: "xyz"
row 3: "lmn", "opq", "rst", "uvw"
For the start I would like to loop over each row and column and output the values in a window.
I was not sure of how to do this since, each row has different number of columns.
Could someone please tell me what would be the best way to initialize this dataset in java?
Thanks
Regards

Option 1:
List<String[]> dataSet = new ArrayList<String[]>();
dataSet.add(new String[] { "abc", "def", "ghi" });
dataSet.add(new String[] { "xyz" });
dataSet.add(new String[] { "lmn", "opq", "rst", "uvw" });
Option 2:
If you know the number of rows in advance, you can also do this:
int numRows = 3; //if you know the number of rows in advance
String[][] dataSet2 = new String[numRows][];
dataSet2[0] = new String[] { "abc", "def", "ghi" };
dataSet2[1] = new String[] { "xyz" };
dataSet2[2] = new String[] { "lmn", "opq", "rst", "uvw" };

First you need to decide how to parse your strings, are they different 1D arrays or all in a 2D array? You could make a 2D array length the size of the largest array and test for nulls in the shorter ones... your simple loop would look something like this:
<code>
for (int i=0; i < 3; i++) {
for (int j=0; j< currentArray.length && currentArray[j] != NULL; j++) {
System.out.println(currentArray[i][j]);
}
}
</code>

Related

How to Add elements at random positions in String array from a String ArrayList. In Android Java

I am new to android java. And this is bugging me.
Here, my ArrayList will have only 3 strings (black, grey, white). But please answer as if it had 100 or 1000 items. Then what would be the code to do that.
ArrayList<String> alCelebrityAllNAMES = new ArrayList<String>();
String myArray = {"1", "2", "3"};
public void regexImagesNames(){
Pattern patternNames = Pattern.compile("/images/banners/(.*?)_234x60.gif");
Matcher matcherNames = patternNames.matcher(fullHtmlCode);
while(matcherNames.find()) {
alCelebrityAllNAMES . add( matcherNames.group(1) ); //yields 3 words(strings)
}
}
This is how I would do it:
Solution 1, the long way...
String[] myArray = new String[]{"1", "2", "3"};
ArrayList<String> alCelebrityAllNAMES = new ArrayList<>(myArray.length);
ArrayList<Integer> alreadyOccupiedIndexes = new ArrayList<>();
for (int i = 0; i < myArray.length; i++)
{
String s = myArray[i];
int randomIndex = new Random().nextInt(myArray.length); // Getting a random index
if(!alreadyOccupiedIndexes.contains(randomIndex))
{
alCelebrityAllNAMES.add(randomIndex, s);
alreadyOccupiedIndexes.add(randomIndex);
i++;
}
}
Solution 2:
alCelebrityAllNAMES.addAll(Arrays.asList(myArray)); // Fill the arrayList with the elements of the array
Collections.shuffle(alCelebrityAllNAMES); // shuffle the elements in it..
// and if you need an array again:
alCelebrityAllNAMES.toArray();

How can I convert a Two D string array to One D string array? [duplicate]

This question already has answers here:
How to flatten 2D array to 1D array?
(9 answers)
Closed 4 years ago.
I have a two dimensional string array:
String myTwoD[][] = {{"Apple", "Banana"}, {"Pork", "Beef"}, {"red",
"green","blue","yellow"}};
How do I convert this to a one dimensional string array as follows in JAVA:
OneD[]={"Apple", "Banana","Pork", "Beef","red", "green","blue","yellow"};
Can ArrayUtils be used for this?
Here is the code for my array, I am trying to store all values in a multipage table column to an array for sorting
for (i=0;i<pagecount; i++)
{
for (j=0;j<columncount;j++)
{
array[i][j]= t.getcolumnname().get(j).getText();
}
}
The simplest way I found out is using stream.
String myTwoD[][] = { { "Apple", "Banana" }, { "Pork", "Beef" }, { "red", "green", "blue", "yellow" } };
List<String[]> list = Arrays.asList(myTwoD);
list.stream().flatMap(num -> Stream.of(num)).forEach(System.out::println);
To store the result into a 1D array. Do this:
String arr[] = list.stream().flatMap(num -> Stream.of(num)).toArray(String[]::new);
for (String s : arr) {
System.out.println("Array is = " + s);
}
There are numerous ways of how you can do it, one way can be first storing the contents of your 2D array to a list and then using it to store the elements in your new 1D array.
In code it looks something like this:
//arr being your old array
ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
list.add(arr[i][j]);
}
}
// now you need to add it to new array
String[] newArray = new String[list.size()];
for (int i = 0; i < newArray.length; i++) {
newArray[i] = list.get(i);
}
try this.
String myTwoD[][] = {{"Apple", "Banana"}, {"Pork", "Beef"},{"red", "green","blue","yellow"}};
List<String> lt = new ArrayList<String>();
for (String[] oneDArray : myTwoD) { //loop throug rows only
lt.addAll(Arrays.asList(oneDArray));
}
String[] oneDArray =(String[])lt.toArray(new String[0]); //conversion of list to array
System.out.println(Arrays.toString(oneDArray)); //code for printing array

Java : Compare previous record with current record in arraylist

I have a sorted array list with 6 elements.The first 5 elements have some value, and the 6th one is empty.
I want to loop through this ArrayList, and compare the first 5 elements of first record, with the same elements in next record. If any one of the element is different, then populate 6th element.
Anyone know an easier and faster approach to do that?
Thanks
Angad
First split the all records into many String[], then parse all values in each. After that you can compare the current record with the first one. Here is an example:
public class StringComparison {
ArrayList<String[]> list = new ArrayList<String[]>();
public void comapreStrings() {
// The list you are comparing everything to
String[] firstRecord = list.get(0);
for(int n = 1; n < list.size(); n++) {
String[] currentRecord = list.get(n);
for (int i = 0; i < currentRecord.length; i++) {
String val1 = firstRecord[i];
String val2 = currentRecord[i];
if (val1.equals(val2)) {
// The two strings are the same
} else {
// Replace "a value" with whatever you want to fill the 6th element with
currentRecord[5] = "a value";
}
}
}
}
Maybe this could be an alternative to think about:
public String[] generateFirstRow(int startingRow) {
final String[] row1 = rowList.get(startingRow);
final String[] row2 = rowList.get(startingRow + 1);
final List<String> list1 = Arrays.stream(row1).collect(toList());
final List<String> toAdd = Arrays.stream(row2).parallel().sorted().filter(s -> !list1.contains(s)).collect(Collectors.toList());
if (list1.get(list1.size() - 1) == "") {
list1.set(list1.size() - 1, toAdd.get(0));
return list1.toArray(new String[0]);
}
return new String[0];
}
Now you can call this per row you have untill the pre-last one.

How do I call for loop into table data?

I have a code where I am getting data when I input values say itr.get(0),str.get(0)etc... But I want to create a for loop to it but I cannot use it since its inside model.addRow
And also each one is of different size array list object(itr,str,dub).
How do I input data through for loop to it so I don't have to call it manually.
public Data1()
{
super();
setDefaultCloseOperation(EXIT_ON_CLOSE);
JTable table = new JTable(new DefaultTableModel(new Object[]{"Integers", "RealNumbers","OtherTokens"},5));
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{itr.get(0),dub.get(0) ,str.get(0) });
model.addRow(new Object[]{itr.get(1),dub.get(1) ,str.get(1) });
model.addRow(new Object[]{itr.get(2),dub.get(2) ,str.get(2) });
model.addRow(new Object[]{itr.get(3), "" ,str.get(3) });
model.addRow(new Object[]{itr.get(4), "" ,str.get(4) });
model.addRow(new Object[]{"", "" ,str.get(5) });
table.setPreferredScrollableViewportSize(new Dimension(500,80));
JScrollPane pane = new JScrollPane(table);
getContentPane().add(pane,BorderLayout.CENTER);
}
The original question asked about adding in a loop to a table. However, the real problem is not the loop per se but rather the fact that there are a different number of elements of different types. This answer takes some data that was presented in the chat, and puts it into arrays. It could be read out of a file. It solves the question of what to put in a given row when there is no data by placing an empty String in the array.
The approach is to use the TableModel rather than attempting to add in a single shot. However, one could construct the necessary array if desired and pass it to the constructor instead. However, the TableModel is a better approach in the long run, IMHO.
public static void main(String[] args)
{
// these three arrays represent the test data otherwise read
// from a file
int[] ia = { 1493, -832722, 0, 1, 162 };
double[] da = { 0.4, -6.382, 9.0E-21 };
String[] sa = { "The", "fox", "jumped", "over", "the", "dog!"};
Object[] columnNames = { "Int", "Real", "Tokens" };
DefaultTableModel dm = new DefaultTableModel(columnNames, 0);
JTable tbl = new JTable(dm);
// while reading for a file, would know the max length in
// a different way
int loopCtr = Math.max(ia.length, da.length);
loopCtr = Math.max(loopCtr, sa.length);
// loop for the longest entry; for each entry decide if there
// is a value
for (int i = 0; i < loopCtr; ++i) {
Integer iv = (i < ia.length ? ia[i] : null);
Double dv = (i < da.length ? da[i] : null);
String sv = (i < sa.length ? sa[i] : "");
//add the row; if no value for a given entry, use an empty
// String
dm.addRow(new Object[]{(iv != null ? iv : ""),
(dv != null ? dv : ""),
sv});
}
//just output for the moment
int cols = dm.getColumnCount();
int rows = dm.getRowCount();
StringBuilder sb = new StringBuilder();
for (int row = 0; row < rows; ++row) {
sb.setLength(0);
for (int col = 0; col < cols; ++col) {
sb.append(dm.getValueAt(row, col));
sb.append("\t");
}
System.out.println(sb.toString());
}
}
The output demonstrates a table with blanks as needed.
1493 0.4 The
-832722 -6.382 fox
0 9.0E-21 jumped
1 over
162 the
dog!

Remove Null array values

I am building an array based off comparing two other arrays. But when I initalize my third array I have to set the length. But that is making my array have null objects in some instances. Is there away I can drop the empty/null postions in the array. See my code so far below:
private String[] tags = new String[] { "Mike", "Bob", "Tom", "Greg" };
private boolean[] selected = new boolean[tags.length];
public String[] selected_tags = new String[tags.length];
for (int i = 0; i < tags.length; i++) {
if (selected[i] == true){
selected_tags[i] = tags[i];
}
}
I left out the code for the checkboxes that builds the Boolen selected [].
Either way if I only select 2 tags then my selected_tags[] array will be Mike, Bob, Null, Null
I need to get the Null Null out. Thanks in advance!
You can use ArrayList, instead of array.
private String[] tags = new String[] { "Mike", "Bob", "Tom", "Greg" };
private boolean[] selected = new boolean[tags.length];
public List<String> selected_tags = new ArrayList<String>();
for (int i = 0; i < tags.length; i++) {
if (selected[i] == true){
selected_tags.add(tags[i]);
}
}
No, you can't drop the null values (and change the length of the array) after you've created it. You'll have to create a new one (or for instance use an ArrayList as illustrated below):
List<String> list = new ArrayList<String>();
for (int i = 0; i < tags.length; i++)
if (selected[i] == true)
list.add(tags[i]);
// Convert it to an array if needed:
selected_tags = list.toArray(new String[list.size()]);
As others have mentioned, this is much easier with an ArrayList. You can even get a regular array from it with the toArray function.
Without using ArrayList, you would have to figure out the length first and not include the null values. As you can see, that's a little messy:
int length = 0;
for( boolean b : selected ) if(b) ++length; // Count the "true"s
String[] selected_tags = new String[length];
for( int i = 0, j = 0; i < tags.length; i++ )
if( selected[i] )
selected_tags[j++] = tags[i];
Instead of using a standard Java array, you should use an ArrayList : it'll allow you to add elements to it, automatically growing the list as needed.
Basically, you'd first declare / instanciate the ArrayList, without specifying any kind of size :
public ArrayList<String> selected_tags = new ArrayList<String>();
And, then, in your loop, you'd use the add() method to add items to that ArrayList :
selected_tags.add(tags[i]);

Categories