Vertically separate arraylist to sublists - java

I have an ArrayList which contains String arrays.
I need to separate this arraylist to sub ArrayLists like separating columns,
like
Arraylist columns to
ArrayList columnOne, ArrayList columnTwo....
No, I need to separate ArrayList to ArrayList like
ArrayList<String[]> data=
["cold","yes"]
["cold","no"]
["hot","no"]
ArrayList<String>
ArrayList<String> columnOne= ["cold","cold","hot"]
ArrayList<String> columnTwo= ["yes","no","no"]
It looks like easy with using loop but may be there is more simple way on initialize ArrayList?

Here is the code you need if I understood well your requirements.
Please adjust the code to test if columnIndex is a valid column index.
You have also to decide what is necessary to do if not all arrays have the same dimension.
public List<String> getColumnList(List<String[]> strArrayList, int columnIndex) {
List<String> columnList = new ArrayList<String>();
for (int i = 0; i < strArrayList.size(); i++) {
columnList.add(strArrayList.get(i)[columnIndex]);
}
return columnList;
}

Related

wanted put array list items into variables using loop

i am dynamically adding items to array-list after i wanted to
Initialize Variables using this array-list items
my array-list is
ArrayList<String> dayCountList = new ArrayList<String>();
i try to do like this but it doesn't work
for (int i = 0; i < dayCountList.size() ;i++) {
double day+"i" = Double.parseDouble(dayCountList.get(i));
}
You can create a array or array list of double type like this.
ArrayList<String> dayCountList = new ArrayList<String>();
.
.
double day[]=new double[dayCountList.size()];
// now use your loop like this
for (int i = 0; i < dayCountList.size() ; i++) {
day[i] = Double.parseDouble(dayCountList.get(i));
}
Now you can call your variables like day[0], for first element
day[1] ,for second and so on.
Hope this helped you.
If you are doing this, then you probably did not understand the purpose of array lists is. One purpose of array list is exactly to avoid creating a whole bunch of variables named day1, day2, day3 and so on.
You seem like you want to transform every element in the array list to a doubles. Why not create another ArrayList<Double> or double[] to store the transformed elements? Instead of writing day1, day2, you can say days.get(0), days.get(1) in the case of array lists. With arrays, you can do days[0], days[1] and so on.
ArrayList<Double> days = dayCountList.stream()
.mapToDouble(Double::parseDouble)
.boxed()
.collect(Collectors.toList());
// or
double[] days = dayCountList.stream()
.mapToDouble(Double::parseDouble).toArray()

Java ArrayList with 2 columns

I need to use an array list as I don't know how many rows I will need but I know I'll need 2 columns. I'm unsure of how to create such an array list, add to both columns and read data from both columns. Both columns will contain integers.
I have seen some suggest:
ArrayList<Arraylist<Integer>> name = new ArrayList<ArrayList<Integer>>();
but I can find an explanation of how to add to both columns.
I've also seen:
ArrayList<Integer[][]> name = new ArrayList<Integer[][]>();
and different variations of where and the number of square brackets.
Thanks.
Java is Object Oriented language, so why not create ArrayList<Column> ?
You can create a class Column which will cover your requirements: it can have setters and getters, and if you need to support other types other than Integer you can generify it. For example:
class Column<T> {
private T value;
public Column(T value) {
this.value = value;
}
public getValue() {
return this.value;
}
}
Then you declare:
List<Column<Integer>> list = new LinkedList<>();
list.add(new Column<Integer>(5));
System.out.println(list.get(0).getValue())
Example how create two dimension structure use lists like you to do:
List<List<Integer>> names = new ArrayList<>();
List<Integer> row = new ArrayList<>();
row.add(1); // first column
row.add(2); // second column
names.add(row); // add row with column
System.out.println(names.get(0).get(0)); // get first column from first row
System.out.println(names.get(0).get(1)); // get second column form first row
But best way is use Custom object like this:
class CustomRow {
private int col1;
private int col2;
// getters and setters
}
List<CustomRow> tables;
CustomRow cr = new CustomRow();
cr.setCol1(1);
cr.setCol2(2);
tables.add(cr);
Something like this:
public MyObject {
Integer integer1;
Integer integer2;
}
List<MyObject> myObjList = new ArrayList<>();
MyObject mo = new MyObject(){
...
myObjList.add(mo);
You could try
a Map and use the key and the value to hold values
a List of tuples
a List of Lists as you suggested
You didn't give enough information as to what you actually want to do, but if you have to use a List as a base, I'd typically go with a List of custom Tuple objects, each holding two values.
You can try creating a simple POJO class called Row and have two variables as column1 and column2. Then add this Row object to your list.
You basically need to create an ArrayList that holds an ArrayList of type Integer. You can then add two of these ArrayLists into the main array list.
List<List<Integer>> myList = new ArrayList<>();
List<Integer> x = new ArrayList<>();
x.add(5);
x.add(6);
List<Integer> y = new ArrayList<>();
y.add(5);
y.add(6);
myList.add(x);
myList.add(y);
Based off this answer:
How do I declare a 2D String arraylist?

How to sort multiple ArrayLists based off order of another?

I'm having trouble figuring out the best way to go out about sorting multiple lists based off of the sorted order of one list. Currently the lists are in order based off their indices. The departureTime list holds strings of time in the format (00:00 AM/PM). They are initialized like this:
public static List<String> departureTime = new ArrayList<String>();
public static List<String> mode = new ArrayList<String>();
public static List<String> busNo = new ArrayList<String>();
public static List<String> busStopName = new ArrayList<String>();
public static List<String> arrivalTime = new ArrayList<String>();
public static List<String> dur = new ArrayList<String>();
I need to sort all lists based of the sorted order of departure times in the departureTime ArrayList. What's the best way to go about sorting these lists without changing the resulting data structure. Any assistance would be highly appreciated.
Thanks,
Matt
As stated in the comment, it would have been easier to create an object containing all the values, and then just sort the object list.
If this is for some reason impossible, you will need to code your own sort method, for instance selection sort, while making the permutations operations on all objects in the lists.
Here is a simple but non optimal algorithm. Feel free to adapt it for some other sort. This would work only if all lists have the same length.
public void sort() {
String[] departureTimeArray = departureTime.toArray(new String[departureTime.size()]);
String[] modeArray = mode.toArray(new String[mode.size()]);
//here you convert the other lists to arrays
int lenD = departureTimeArray.length;
int j = 0;
for(int i=0;i<lenD;i++){
j = i;
for(int k = i;k<lenD;k++){
if(departureTimeArray[j].compareTo(departureTimeArray[k])>0){
j = k;
}
}
permutation(departureTimeArray, i, j);
permutation(modeArray, i, j);
//here do the same for other arrays
}
departureTime = Arrays.asList(departureTimeArray);
mode = Arrays.asList(modeArray);
//here convert back arrays to list
}
private void permutation(String[] array, int i, int j) {
String tmp = array[i];
array[i] = array[j];
array[j] = tmp;
}
See for instance here for the selection sort algorithm :
selection sort
You could save the index of each departure time before sorting in a Hashmap<String, Integer>. Then sort only that list as usual, then save again the indexes in another hashmap.
Now you know that a given string was in position n before sorting and is now in position n' after sorting. So you can manually swap the other lists's elements with this info.
This approach is brittle, because if there were repeated elements in the list, then you can't know which one was which after sorting. So you are better off creating a container class as suggested in the other answers.

Java - iterate over ArrayList rows' (columns)?

What is the simplest way to just iterate over ArrayList rows values?
For example I have two ArrayList:
ArrayList<Object> main = new ArrayList<Object>();
ArrayList<Object> row = new ArrayList<Object>();
I use two fors to add values into main. First I add row, then when row iterations end, I add it to main, and then repeat for another row etc. For example:
for(int i=0; i < somearray.length; i++){
for(int j=0; j < somearray2.length; j++){
if(somearray2[j] == true)
row.add(somearray2[j]);
}
main.add(row);
}
So now I get ArrayList filled with rows like I need. But later I need to iterate over rows values, not just rows themselves from main ArrayList. How can I do that?
As I only see the method:
main.get(index), which let's me get a row, but nothing more.
So, based on your description, main is not a list of Objects, but a list of lists. So it should be declared as
List<List<Object>> main = new ArrayList<>();
The iteration now becomes obvious:
for (List<Object> row : main) {
for (Object element : row) {
// do what you want here
}
}
This has the additional advantage of making your code type-safe: you won't be able to add, inadvertently, anything other than a List<Object> inside the main list.
Yes then access them as: ((ArrayList<Object>)main.get(index)).get(index2);. But if you want all of your row element to be added to main array, you can make use of:
Collections.addAll(main, row.toArray());

Remove a specific string from an array of string

I have an array like this:
String n[] = {"google","microsoft","apple"};
What I want to do is to remove "apple".
My problem is very basic,however,I searched the website and I found out that java doesn't really support the deleting feature from an array.I also heard to use Java Utils, because it's so simple to remove an item....I tried to find Java Utils on google, but almost all links are dead.
So finally...is there any way to remove a string from an array of string?
Even if I use an ArrayList I can't find a method to generate a random item in it! For ex: in a normal array I generate a string like this:
String r = myAL[rgenerator.nextInt(myAL.length)];
In an arraylist it doesn't work....maybe you know a solution...
Define "remove".
Arrays are fixed length and can not be resized once created. You can set an element to null to remove an object reference;
for (int i = 0; i < myStringArray.length(); i++)
{
if (myStringArray[i].equals(stringToRemove))
{
myStringArray[i] = null;
break;
}
}
or
myStringArray[indexOfStringToRemove] = null;
If you want a dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly, use an ArrayList<String>
myArrayList.remove(stringToRemove);
or
myArrayList.remove(indexOfStringToRemove);
Edit in response to OP's edit to his question and comment below
String r = myArrayList.get(rgenerator.nextInt(myArrayList.size()));
It is not possible in on step or you need to keep the reference to the array.
If you can change the reference this can help:
String[] n = new String[]{"google","microsoft","apple"};
final List<String> list = new ArrayList<String>();
Collections.addAll(list, n);
list.remove("apple");
n = list.toArray(new String[list.size()]);
I not recommend the following but if you worry about performance:
String[] n = new String[]{"google","microsoft","apple"};
final String[] n2 = new String[2];
System.arraycopy(n, 0, n2, 0, n2.length);
for (int i = 0, j = 0; i < n.length; i++)
{
if (!n[i].equals("apple"))
{
n2[j] = n[i];
j++;
}
}
I not recommend it because the code is a lot more difficult to read and maintain.
Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.
You can't remove anything from an array - they're always fixed length. Once you've created an array of length 3, that array will always have length 3.
You'd be better off with a List<String>, e.g. an ArrayList<String>:
List<String> list = new ArrayList<String>();
list.add("google");
list.add("microsoft");
list.add("apple");
System.out.println(list.size()); // 3
list.remove("apple");
System.out.println(list.size()); // 2
Collections like this are generally much more flexible than working with arrays directly.
EDIT: For removal:
void removeRandomElement(List<?> list, Random random)
{
int index = random.nextInt(list.size());
list.remove(index);
}
import java.util.*;
class Array {
public static void main(String args[]) {
ArrayList al = new ArrayList();
al.add("google");
al.add("microsoft");
al.add("apple");
System.out.println(al);
//i only remove the apple//
al.remove(2);
System.out.println(al);
}
}

Categories