Sublists in a 2D List, Referencing - java

I have a 2D List of objects. I'm trying to access a list and replace it with a sublist of itself. I made up a simple example below, I want to replace dList.get(0) with dList.get(0).subList(1,3). I use a reference variable, which updates the values in the original list, but the subList is not getting updated. I`m a bit new to this, any help in the form of examples, explanations and directing me documentation is appreciated.
List<List<Double>> dList = new ArrayList<List<Double>>();
/**
* Initialize, the 2D List with some values
*/
protected void init() {
List<Double> d = new ArrayList<Double>();
d.add(1.0);
d.add(2.0);
d.add(3.0);
d.add(4.0);
d.add(5.0);
dList.add(d);
}
/**
* Check if the subList update works.
*/
protected void check() {
List<Double> tmp = dList.get(0); //get the reference into a temporary variable
tmp = tmp.subList(1, 3); //get the sublist, in the end the original list dList.get(0) should be this.
tmp.set(0, 4.5); //reference works, the dList.get(0) values get updated
for (int i = 0; i < tmp.size(); i++) {
System.out.println(tmp.get(i));
}
System.out.println("....Original 2D List Values....");
for (int i = 0; i < dList.get(0).size(); i++) {
System.out.println(dList.get(0).get(i)); // still has all the elements, and not the sublist
}
System.out.println("Result" + dList.get(0).size());
}

tmp.subList() returns a new List instance that is different from the first element of dList. That's why the original List was unchanged.
You need to set the first element of dList to refer to the sub-list you created :
List<Double> tmp = dList.get(0);
tmp = tmp.subList(1, 3);
tmp.set(0, 4.5);
dList.set (0, tmp);

Related

Need help useing a Iterator in java

I am trying to print out a array list of linked lists of size 8 using an Iterator here is what I have so far
ArrayList<LinkedList> myaol = new ArrayList<>();//my array which the linked lists are created when needed
public void printList(Iterator<Gen> itr)//gen is the generic data type
{
while( this.hasNext() )
{
System.out.println(this.next());
}
}
I under stand how to iterate through one linked list but am not sure how to go to the next index of the the arraylist in order to get every linked list any help would be much appreciated
Since you have an ArrayList of LinkedLists, you can get each LinkedList with the following code, and do whatever you want to do with the LinkedLists...
ArrayList<LinkedList> myaol = new ArrayList<>();
Iterator<LinkedList> itr = myaol.iterator();
while (itr.hasNext()) {
LinkedList myList = itr.next();
}
You can print the list like that
// print the list
System.out.println("LinkedList:" + myList);
// create an array and copy the list to it
Object[] array = myList.toArray();
// print the array
for (int i = 0; i < myList.size(); i++) {
System.out.println("Array:" + array[i]);
}

Swaping the elements of a list

i am having a List of objects and i i wants to do some operation on the list in such a way that the a particular object should be shifted to list position 0 and the the object at position 0 will take place the shifted object. the diagram is as shown below.
the list is as follows
final List<Object> list= new ArrayList<Object>();
presently i have made two temporary lists as
final List<Object> temp1= new ArrayList<Object>();
final List<Object> temp2= new ArrayList<Object>();
to do the operation i am running a loop and on particular condition adding object to temp1 else adding to temp2 , something like as follows :
for (int i = 0; i < 5; i++) {
if (i==3) {
temp1.add(i);
} else {
temp2.add(i);
}
}
and finally doing
list.addAll(temp1);
list.addAll(temp2);
how to do the same logic in redundant and effective steps rather than using temp lists.
Use this swap method:
Collections.swap(List<?> list, int i, int j);
Try this code:
Object temp = list.get(0);
list.set(0, list.get(3));
list.set(3, temp);

Remove elements from ArrayList

I have to remove elements from ArrayList, but I have not gone through it. Elements which I have to remove are also available in ArrayList. In short, I have to remove one Array List from another Array List. e.g. Suppose
ArrayList<String> arr1= new ArrayList<String>();
ArrayList<String> arr2 = new ArrayList<String>();
arr1.add("1");
arr1.add("2");
arr1.add("3");
arr2.add("2");
arr2.add("4");
Now, I have to remove elements which are in arr2 from arr1. So, that I have final answer as 1 and 3.
What needs to be done?
Read Remove Common Elements in Two Lists Java
Use below code
List<String> resultArrayList = new ArrayList<String>(arr1);
resultArrayList.removeAll(arr2);
Or can be done by
arr1.removeAll(arr2)
After SO comments
I used the following code
ArrayList<String> arr1= new ArrayList<String>();
ArrayList<String> arr2 = new ArrayList<String>();
arr1.add("1");
arr1.add("2");
arr1.add("3");
arr2.add("2");
arr2.add("4");
System.out.println("Before removing---");
System.out.println("Array1 : " + arr1);
System.out.println("Array2 : " + arr2);
System.out.println("Removing common ---");
List<String> resultArrayList = new ArrayList<String>(arr1);
resultArrayList.removeAll(arr2);
System.out.println(resultArrayList);
and getting output as
Before removing---
Array1 : [1, 2, 3]
Array2 : [2, 4]
Removing common ---
[1, 3]
So what is not working at your side?
Read more about How do you remove the overlapping contents of one List from another List?
Take new arr as final sorted array
for(int i=0;i<arr1.size();i++)
{
for(int j=0;j<arr2.size();j++)
if(!arr1.get(i).contains(arr2.get(j)))
{
arr.add(arr1.get(i));
}
}
You can use removeAll() function
/**
* Removes from this list all of its elements that are contained in the
* specified collection.
*
* #param c collection containing elements to be removed from this list
* #return {#code true} if this list changed as a result of the call
* #throws ClassCastException if the class of an element of this list
* is incompatible with the specified collection
* (optional)
* #throws NullPointerException if this list contains a null element and the
* specified collection does not permit null elements
* (optional),
* or if the specified collection is null
* #see Collection#contains(Object)
*/
public boolean removeAll(Collection<?> c) {
return batchRemove(c, false);
}
To remove duplicate of one from other use this
int arr1Size = arr2.size();
int arr2Size = arr2.size();
for (int i = 0; i < arr1Size; i++)
{
for (int j = 0; j < arr2Size; j++)
{
if (arr1.get(i).contains(arr2.get(j)))
{
arr1.remove(i);
}
}
}
System.out.print(arr1);
Ok to make things clear:
if your list is composed of basic elements such as String etc
all you need to do is use
list2.removeAll(list1);
assuming that isnt the case meaning you created a list from custum objects - the above method wont work, that is due to the nature of the item comparison.
it uses the object.equals method which by default checks if this is the same instance of the object in the other list (which it probably isnt)
so in order for this to work you need to overwrite the custom object equals method.
example - test if 2 contacts are the same based on phone number:
public boolean equals(Object o)
{
if (o==null)
{
return false;
}
if (o.getClass()!=this.getClass())
{
return false;
}
Contact c=(Contact)o;
if (c.get_phoneNumber().equals(get_phoneNumber()))
{
return true;
}
return false;
}
now if you use
list2.removeAll(list1);
it will compare the items based on the desired attribute (in the example based on phone number) and will work as planned.

How to move data from multiple Arraylist to multiple Arrays (in Java)

I have 3 arraylist each have size = 3 and 3 arrays also have length = 3 of each. I want to copy data from arraylists to arrays in following way but using any loop (i.e for OR for each).
myArray1[1] = arraylist1.get(1);
myArray1[2] = arraylist2.get(1);
myArray1[3] = arraylist3.get(1);
I have done it manually one by one without using any loop, but code appears to be massive because in future I'm sure that number of my arraylists and arrays will increase up to 15.
I want to copy the data from arraylists to arrays as shown in the image but using the loops not manually one by one?
How about this?
List<Integer> arraylist0 = Arrays.asList(2,4,3);
List<Integer> arraylist1 = Arrays.asList(2,5,7);
List<Integer> arraylist2 = Arrays.asList(6,3,7);
List<List<Integer>> arraylistList = Arrays.asList(arraylist0, arraylist1, arraylist2);
int size = 3;
int[] myArray0 = new int[size];
int[] myArray1 = new int[size];
int[] myArray2 = new int[size];
int[][] myBigArray = new int[][] {myArray0, myArray1, myArray2};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
myBigArray[i][j] = arraylistList.get(j).get(i);
}
}
To explain, since we want to be able to work with an arbitrary size (3, 15, or more), we are dealing with 2-dimensional data.
We are also dealing with array and List, which are slightly different in their use.
The input to your problem is List<Integer>, and so we make a List<List<Integer>> in order to deal with all the input data easily.
Similarly, the output will be arrays, so we make a 2-dimensional array (int[][]) in order to write the data easily.
Then it's simply a matter of iterating over the data in 2 nested for loops. Notice that this line reverses the order of i and j in order to splice the data the way you intend.
myBigArray[i][j] = arraylistList.get(j).get(i);
And then you can print your answer like this:
System.out.println(Arrays.toString(myArray0));
System.out.println(Arrays.toString(myArray1));
System.out.println(Arrays.toString(myArray2));
You need to have two additional structures:
int[][] destination = new int [][] {myArray1, myArray2,myArray3 }
List<Integer>[] source;
source = new List<Integer>[] {arraylist1,arraylist2,arraylist3}
myArray1[1] = arraylist1.get(1);
myArray1[2] = arraylist2.get(1);
myArray1[3] = arraylist3.get(1);
for (int i=0;i<destination.length;i++) {
for (int j=0;j<source.length;j++) {
destination[i][j] = source[j].get(i);
}
}
If you cannot find a ready made API or function for this, I would suggest trivializing the conversion from List to Array using the List.toArray() method and focus on converting/transforming the given set of lists to a another bunch of lists which contain the desired output. Following is a code sample which I would think achieves this. It does assume the input lists are NOT of fixed/same sizes. Assuming this would only make the logic easier.
On return of this function, all you need to do is to iterate over the TreeMap and convert the values to arrays using List.toArray().
public static TreeMap<Integer, List<Integer>> transorm(
List<Integer>... lists) {
// Return a blank TreeMap if not input. TreeMap explanation below.
if (lists == null || lists.length == 0)
return new TreeMap<>();
// Get Iterators for the input lists
List<Iterator<Integer>> iterators = new ArrayList<>();
for (List<Integer> list : lists) {
iterators.add(list.iterator());
}
// Initialize Return. We return a TreeMap, where the key indicates which
// position's integer values are present in the list which is the value
// of this key. Converting the lists to arrays is trivial using the
// List.toArray() method.
TreeMap<Integer, List<Integer>> transformedLists = new TreeMap<>();
// Variable maintaining the position for which values are being
// collected. See below.
int currPosition = 0;
// Variable which keeps track of the index of the iterator currently
// driving the iteration and the driving iterator.
int driverItrIndex = 0;
Iterator<Integer> driverItr = lists[driverItrIndex].iterator();
// Actual code that does the transformation.
while (driverItrIndex < iterators.size()) {
// Move to next driving iterator
if (!driverItr.hasNext()) {
driverItrIndex++;
driverItr = iterators.get(driverItrIndex);
continue;
}
// Construct Transformed List
ArrayList<Integer> transformedList = new ArrayList<>();
for (Iterator<Integer> iterator : iterators) {
if (iterator.hasNext()) {
transformedList.add(iterator.next());
}
}
// Add to return
transformedLists.put(currPosition, transformedList);
}
// Return Value
return transformedLists;
}

Getting old positions of ArrayList items in Android

I have an ArrayList named play_viewCount: I am sorting this ArrryList and storing it in a new ArrayList.
Now I have sorted ArrayList: but what I want is before sorting what was the position of new items in ArrayList?
ArrayList<String> sort_play_viewCount = play_ViewCount; // here play_viewCount is ArrayList
ArrayList<Integer> position_array = new ArrayList<Integer>();
System.out.println("......................................... Play Count :"+sort_play_viewCount);
Collections.sort(sort_play_viewCount);
System.out.println(".........................................sort Play Count :"+sort_play_viewCount);
for(int j = 0; j<sort_play_viewCount.size(); j++){
for(int k = 0; k<sort_play_viewCount.size(); k++){
if(play_ViewCount.contains(sort_play_viewCount.get(j))){
position_array.add(k);
}
}
}
System.out.println(" .................Position Array: "+position_array);
Does anyone know how to get the positions of the new items before sorting?
Try doing a little differently:
ArrayList<Integer> position_array = new ArrayList<Integer>();
position_array.addAll(play_viewCount);
Collections.sort(position_array);
Now position_array is sorted, and to get the previous positions you can just call play_viewCount.indexOf(value);
You can put the elements of the ArrayList into a Map<String, Integer> (implemented by a HashMap<String, Integer>), where the key of an entry is String element from the ArrayList and the value is Integer representing the position.
Map<String, Integer> originalPositions = new HashMap<String, Integer>();
String item = ...
String position = ...
originalPositions.put(item, position);
// do something with the ArrayList, such as sorting
Collections.sort(arrayList);
String someItem = arrayList.get(i);
int originalPosition = originalPositions.get(someItem);
And by the way, this line from your code snippet doesn't do what you think it does:
ArrayList<String> sort_play_viewCount = play_ViewCount;
It doesn't create a new ArrayList with the same contents as the original one. Instead, it just creates a new reference to the original ArrayList. Both play_ViewCount and sort_play_viewCount refer to the very same object, in other words, any changes to one of the variables (such as sorting) also affect the other one.
To create a new copy (however, it is still shallow) of an ArrayList, use the following idiom:
ArrayList<Integer> original = ...
ArrayList<Integer> copy = new ArrayList<Integer>(original);

Categories