Adding values from an arraylist of an arraylist - java

Does anyone know how I can sum the values in an arraylist contained inside an arraylist?
For e.g.
ArrayList<Double> arr1=new ArrayList<Double>;
ArrayList<Double> arr2=new ArrayList<Double>;
Let say: arr1=[4.5,6.7,8.9,7.3,4.5]
arr2=[5.6,7.8,1.3,4.5,3.2]
ArrayList<ArrayList<Double>> arrayListOfarr1_arr2=new ArrayList<ArrayList<Double>>();
arrayListOfarr1_arr2.add(arr1);
arrayListOfarr1_arr2.add(arr2);
How can I it such that both of the arrayList values can be added together when it points to the same index inside the arrayList the contains them?
For e.g.
sum_of_arr1_arr2=[10.1,14.5,10.2,11.8,7.7]

You just need to iterate through your array lists, like so
List arr3<Double> = new ArrayList<Double>();
// Set the loop to the size of the smallest array
int loopSize = arr1 < arr2 ? arr1.size() : arr2.size();
for (int x = 0 ; x < loopSize ; x++) {
arr3.add(arr1.get(x) + arr2.get(x));
}
Also, in general we should always try to use List<T> myList = new ArrayList<T>(); instead of ArrayList<T> myList = new ArrayList<T>();.

Related

Is there a way of generating random numbers from an ArrayList?

I have an ArrayList that contains numbers (1-50). Now I want to generate random numbers from this ArrayList (each random number must be an item from the ArrayList) and once that item is picked, it will be remove from the ArrayList.
This is what I have tried but the Random object keeps generating numbers that are not in the ArrayList
Random rnd = new Random();
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
while (list2.size() < 50) {
int index = list1.get(rnd.nextInt(list1.size()));
list2.add(index);
list1.remove(index);
}
The above code keeps generating random numbers that are not in the list1 object.
I need only numbers that are in list1 to be generated.
From what I understand, you are picking a random number from one list, removing it (note that there's a difference in remove(Integer o) and remove(int index)) , and inserting into another.
This is the exact same operation as shuffling the original list, making a copy, then clearing it
List<Integer> list1 = IntStream.range(1,51).collect(Collectors.toList());
Collections.shuffle(list1);
List<Integer> list2 = new ArrayList<>(list1);
list1.clear();
Try this:
while (list2.size() < 50) {
int index = rnd.nextInt(list1.size());
list2.add(list1.remove(index));
}
UPDATE:
BTW: index is an int, not an Integer, so list1.remove(index) removes the element at given index, and not the element with given value.
I suggest you simply shuffle the original list.
List<SomeObject> objects = new ArrayList<>();
Collections.shuffle(objects);
Now, take the value from the end (more efficient for ArrayLists), and then delete it.
int last = objects.size()-1;
while (last >= 0) {
SomeObject ob = objects.get(last);
objects.remove(last--);
// now do whatever you want with ob
}
Please pay attention to the line #7:
Random rnd = new Random();
ArrayList<Integer> list1 = new ArrayList<>();
ArrayList<Integer> list2 = new ArrayList<>();
while (list2.size() < 50) {
int index = list1.get(rnd.nextInt(list1.size()));
list2.add(index); <-- you are adding random index here instead of list1's value
list1.remove(index);
}
Finally I got the issue solved by shuffling the list1 object before putting them to list2
Collection.shuffle(list1);
for (int i=0; i<=50; i++){
list2.put(list1(i);
}
This gave me exactly what i wanted.
Thanks everyone for your contributions

How do I loop thorough a 2D ArrayList in Java and fill it?

I am trying to use 2D arrayLists in Java.
I have the definition:
ArrayList<ArrayList<Integer>> myList = new ArrayList<ArrayList<Integer>>();
How can I loop through it and enter in numbers starting from 1?
I know that I can access a specific index by using:
myList.get(i).get(j)
Which will get the value. But how do I add to the Matrix?
Thanks
You can use a nested for loop. The i-loop loops through the outer ArrayList and the j-loop loops through each individual ArrayList contained by myList
for (int i = 0; i < myList.size(); i++)
{
for (int j = 0; j < myList.get(i).size(); j++)
{
// do stuff
}
}
Edit: you then fill it by replacing // do stuff with
myList.get(i).add(new Integer(YOUR_VALUE)); // append YOUR_VALUE to end of list
A Note: If the myList is initially unfilled, looping using .size() will not work as you cannot use .get(SOME_INDEX) on an ArrayList containing no indices. You will need to loop from 0 to the number of values you wish to add, create a new list within the first loop, use .add(YOUR_VALUE) to append a new value on each iteration to this new list and then add this new list to myList. See Ken's answer for a perfect example.
Use for-each loop, if you are using Java prior 1.5 version.
for(ArrayList<Integer> row : myList) {
for(Integer intValue : row) {
// access "row" for inside arraylist or "intValue" for integer value.
}
}
Assuming the matrix is not initialized,
int m = 10, n = 10;
ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < m; i++) {
List<Integer> row = new ArrayList<Integer>();
for (int j = 0; j < n; j++) {
row.add(j);
}
matrix.add(row);
}

Clear() function for Arraylist in Arraylist

I am trying to add an arraylist in an arraylist in a for loop. When I clear the data in second one, it clears in second arraylist data in first arraylist. Let me explain with code:
ArrayList arrTemp = new ArrayList();
ArrayList arrTemp2 = new ArrayList();
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
//Here I add some strings in arrTemp
}
arrTemp2.add(arrTemp); //I will add arrTemp 10 times with different data in it to arrTemp2
arrTemp.clear(); //Everytime I want to clear the arrTemp
//But when I clear it, it also clears already added arrTemp in arrTemp2
}
I want it to have 10 different arrTemp in arrTemp2
for(int i = 0; i < 10; i++)
{
arrTemp = new ArrayList();
for(int j = 0; j < 10; j++)
.....
You will have different array for each i.
arrTemp2.add(arrTemp);// will add arrTemp object's reference to your arrTemp2.
So, once you clear arrTemp, you actually will clear() the space being pointed by arrTemp.
use Generics with addAll(), like this:
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(2);
ArrayList<Integer> al2 = new ArrayList<Integer>();
al2.add(3);
al.addAll(al2);
al2.clear();
System.out.println(al);
}
O/P :
[1, 2, 3]
Your case :
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(1);
al.add(2);
ArrayList al2 = new ArrayList();
al2.add(3);
al.add(al2);
al2.clear();
System.out.println(al);
}
O/P :
[1, 2, []] // 3rd item is considered as an Object
I'm not positive, but it seems to me that your addTemp2.add(arrTemp) is not working as intended. Have you tried debugging and checking whether arrTemp2 is actually being populated with something after that line fires? Looking at the documentation (below) for ArrayLists, I think you might want addAll instead. Alternately, you could iterate over arrTemp and add each element individually to arrTemp2 before you clear arrTemp.
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Easy..
Replace
arrTemp.clear(); with arrTemp = new ArrayList();

Delete those elements from the list that are indexed in another list

List<Double> elements = new ArrayList<Double>();
List<Integer> usedElements = new ArrayList<Integer>();
for (int i=0; i<usedElements.size(); i++)
{
elements.remove(usedElements.get(i));
}
There is a List of indexes called usedElements. I need to delete those elements from the List elements that are mentioned in usedElements. How to do this in a correct way.
If you know your usedElements list is in ascending order, the simplest approach would be to remove the elements in reverse order - that way the "shuffling up" effect won't affect any of the later operations:
List<Double> elements = ...;
List<Integer> usedElements = ...;
for (int i = usedElements.size() - 1; i >= 0; i--) {
elements.remove(usedElements.get(i));
}
If usedElements isn't currently sorted, it would be best to just sort it first. If usedElements isn't currently sorted and you need to maintain its current order for another reason, then create a copy first, and sort that:
List<Double> elements = ...;
List<Integer> usedElements = ...;
List<Integer> sortedUsedElements = new ArrayList<Integer>(usedElements);
Collections.sort(sortedUsedElements);
for (int i = sortedUsedElements.size() - 1; i >= 0; i--) {
elements.remove(sortedUsedElements.get(i));
}
Or even sort the copy in reverse order and use an enhanced for loop:
List<Double> elements = ...;
List<Integer> usedElements = ...;
List<Integer> sortedUsedElements = new ArrayList<Integer>(usedElements);
Collections.sort(sortedUsedElements, Collections.<Integer>reverseOrder());
for (Integer index : sortedUsedElements) {
elements.remove(index);
}
You might find it easier to create a new list instead of trying to modify the original list in place:
Set<Integer> used = new HashSet<>(usedElements); // maybe use a set in the
// first place?
List<Integer> newElements =
new ArrayList<>(elements.size() - used.size());
for (int i = 0; i < elements.size(); i++) {
if (!used.contains(i))
newElements.add(elements.get(i));
}
elements = newElements;
This entire process is O(n).

Clean way to initialize an arraylist

I want an Arraylist in Java, which I want to fill with 10's
ArrayList<Integer> list = new ArrayList<Integer>(100);
for (int i = 0; i < 100; i++) {
list.add(10);
}
I'm going to have to initialize a lot of Arraylists, so I was wondering if there is there a clean way to do this without a for loop?
You can use Collections.nCopies:
ArrayList<Integer> list = new ArrayList<Integer>(Collections.nCopies(100, 10));
This will initialize list with 100 10's.
ArrayList<Integer> list = new ArrayList<Integer>(100);
for (int i = 0; i < list.size(); i++)
{
list.add(10);
}
list.size() will be 0 here, so this is why your code does not work. size keeps track of how many elements are currently in the list, not the capacity.
If you want the ArrayList to be initialized with all 10s, you can use:
ArrayList<Integer> list = new ArrayList<Integer>(Collections.nCopies(100, 10));
Edit: You said later that you didn't want a for loop, but to fix your code, just replace list.size() with 100.

Categories

Resources