Swaping the elements of a list - java

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);

Related

JAVA Get each value of arraylist

I have one arraylist that contain two list
like this
[[asd, asswwde, efef rgg], [asd2223, asswwd2323e, efef343 rgg]]
My Code is
ArrayList<String> create = new ArrayList<String>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
inner.add("asd");
inner.add("asswwde");
inner.add("efef rgg");
inner1.add("asd2223");
inner1.add("asswwd2323e");
inner1.add("efef343 rgg");
create.add(inner.toString());
create.add(inner1.toString());
i have to get all value one by one of every index of that arraylist
So what is the best way to get these all value one by one.
I am using JAVA with Eclipse Mars.
Just use two nested loops:
List<List<Object>> list = ...;
for (List<Object> subList : list) {
for (Object o : subList) {
//work with o here
}
}
You may also want to consider replacing the inner lists by proper objects.
You want to loop through the outside ArrayList and then loop through each ArrayList within this ArrayList, you can do this by using the following:
for (int i = 0; i < outerArrayList.size(); i++)
{
for (int j = 0; j < outerArrayList.get(i).size(); j++)
{
String element = outerArrayList.get(i).get(j);
}
}
Here is another verison you may find easier to understand, but is essentially the same:
for (int i = 0; i < outerArrayList.size(); i++)
{
ArrayList<String>() innerArrayList = outerArrayList.get(i)
for (int j = 0; j < innerArrayList.size(); j++)
{
String element = innerArrayList.get(j);
}
}
or alternatively again using a foreach loop:
for (ArrayList<String> innerArrayList : outerArrayList)
{
for (String element : innerArrayList)
{
String theElement = element;
}
}
It might be worth noting that your ArrayList appears to contain different types of elements - is this definitely what you wanted to do? Also, make sure you surround your strings with "" unless they are variable names - which it doesn't appear so.
EDIT: Updated elements to type String as per your update.
I would also recommend you change the type of your create ArrayList, like below, as you know it will be storing multiple elements of type ArrayList:
ArrayList<ArrayList> create = new ArrayList<ArrayList>();
Try to use for loop nested in foreach loop like this:
for(List list : arrayListOfList)
{
for(int i= 0; i < list.size();i++){
System.out.println(list.get(i));
}
}
I'm not sure if the data structures are part of the requirements, but it would be better constructed if your outer ArrayList used ArrayList as the generic type.
ArrayList<ArrayList<String>> create = new ArrayList<ArrayList<String>>();
ArrayList<String> inner = new ArrayList<String>();
ArrayList<String> inner1 = new ArrayList<String>();
...
create.add(inner);
create.add(inner1);
Then you could print them out like this:
for(List list : create) {
for (String val : list) {
System.out.println(val);
}
}
Othewise, if you stick with your original code, when you add to the outer list you are using the toString() method on an ArrayList. This will produce a comma delimited string of values surrounded by brackets (ex. [val1, val2]). If you want to actually print out the individual values without the brackets, etc, you will have to convert the string back to an array (or list) doing something like this:
for (String valList : create) {
String[] vals = valList.substring(1, val.length() - 1).split(",");
for (String val : vals) {
System.out.println(val.trim());
}
}

Filter ArrayList and remove unwanted elements

I have a ArrayList that contains elements (fields are name and type). There are only two different possible types ("edu" and "ent") that I want each to be displayed in its own listview.
My idea was to create two new ArrayLists with same data and then loop through each and filter unwanted elements like this:
ListView listView_ent = (ListView) findViewById(R.id.popular_apps_list_ent);
ArrayList<DataHolder> data_ent = data;
for (int i = 0; i < data_ent.size(); i++) {
if(data_ent.get(i).getType().equals("edu")){
data_ent.remove(i);
}
}
listView_ent.setAdapter(new AppsAdapter(this, data_ent));
ListView listView_edu = (ListView) findViewById(R.id.popular_apps_list_edu);
ArrayList<DataHolder> data_edu = data;
for (int i = 0; i < data_edu.size(); i++) {
if(data_edu.get(i).getType().equals("ent")){
data_edu.remove(i);
}
}
listView_edu.setAdapter(new AppsAdapter(this, data_edu));
There are 10 elements in ArrayList, 5 of each type.
Problem is that at the end in the both listviews there are 4 same items displayed with mixed types.
Any idea what I did wrong?
1) copy the data
2) don't iterate using i and remove; use an iterator (remove method: http://docs.oracle.com/javase/7/docs/api/java/util/Iterator.html#remove()) or start at the end of the list
something like this:
ListView listView_ent = (ListView) findViewById(R.id.popular_apps_list_ent);
ArrayList<DataHolder> data_ent = new ArrayList( data);
for (int i = data_ent.size()-1; i >= 0; i--) {
if(data_ent.get(i).getType().equals("edu")){
data_ent.remove(i);
}
}
listView_ent.setAdapter(new AppsAdapter(this, data_ent));
ListView listView_edu = (ListView) findViewById(R.id.popular_apps_list_edu);
ArrayList<DataHolder> data_edu = = new ArrayList( data);
for (int i = data_edu.size()-1; i >= 0 ; i--) {
if(data_edu.get(i).getType().equals("ent")){
data_edu.remove(i);
}
}
listView_edu.setAdapter(new AppsAdapter(this, data_edu));
Yes, assignment will just copy the value of data_ent (which is a reference) to data_edu. They will both refer to the same object. So whatever changes you make in either list, same changes will reflect in the other list as well
This is you should do :-
List<Integer> data_edu = new ArrayList<Integer>(data_ent);
or use the addAll() function of array list.
Once you remove an item from your ArrayList, the indeces all shift down. You can either add in i-- after remove, or use an iterator:
Iterator<DataHolder> i = data_edu.iterator();
while (i.hasNext()) {
DataHolder d = i.next();
if (d.getType().equals(...) {
i.remove();
}
}
Rahul is correct regarding list references, but you have another problem as well.
ListView listView_ent = (ListView) findViewById(R.id.popular_apps_list_ent);
ArrayList<DataHolder> data_ent = data;
for (int i = 0; i < data_ent.size(); i++) {
if(data_ent.get(i).getType().equals("edu")){
data_ent.remove(i);
}
}
The problem is that when you remove, you bugger your indices. You're essentially skipping items. Consider
{"edu", "edu", "ent"}
Once you take out the first item (index 0), the second edu becomes the new index 0, but you move on and check index 1.
Try using a ListIterator http://docs.oracle.com/javase/6/docs/api/java/util/ListIterator.html
hint:
ListIterator<DataHolder> entDataIterator = data_ent.listIterator();
while(entDataIterator.hasNext(){
if(/*whatever*/){
entDataIterator.remove();
}
}
In your for for loops, you may be skipping items. Let's say your list is something like that:
list = {edu, edu, ent, ent, edu}
Your index variable will be i = 0. list[i] == "edu" then you remove it, but then your list becomes:
list = {edu, ent, ent, edu}
But your index variable gets incremented and is then equals to 1. and list[1] = "ent". As you undersand you are not processing the first element of the list. You skipped indices.
Hope this is clear.
If you have commons-collections available in your project, you may as well use the filter method on CollectionUtils:
CollectionUtils.filter(your_list, new Predicate() {
#Override
public boolean evaluate(Object obj) {
return !((DataHolder) obj).getType().equals("edu");
}
});
Your remove loop is wrong. You can use this: for (int i= data_end.size - 1, i >=0, i--)
Think about feature extension later? Use more than 2 types?
The solution is very simple. Your code a filter function first
public List<DataHolder> filterBy(List<DataHolder> list, String type) {
List<DataHolder> l = new ArrayList<>();
for ( DataHolder h : list) {
if (h.getType().equals(type)) {
l.add(h);
}
}
return l;
}
Use the filter function:
List<DataHolder> eduList = filterBy(data, "edu");
listView_edu.setAdapter(new AppsAdapter(this, eduList));
List<DataHolder> entList = filterBy(data, "ent");
listView_ent.setAdapter(new AppsAdapter(this, entList));
Consider using Guava library for filtering collections:
http://www.motta-droid.com/2013/12/collections-performance-tests-in.html
In example above, filter returns new filtered collection don't affecting source collection. Maybe it's not worth time to add a library for one small task and if collections don't contain much items, but it's a good tool to be familiar with.

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 most recent objects in a list

How can i get the most recent objects in a List?
I have tried
int i = 5;
while(i > 0) {
Object o = list.get(list.size() - i);
i--;
}
but to no avail, i could be doing it wrong, but if i am i am unware how to fix my mistake :/
(The problem is it is still giving me the entire list)
You could just reverse the list then iterate over it:
// Your original list
List<Object> list = new ArrayList<Object>(); // Populated elsewhere
// Make a copy, so you don't corrupt the original list
List<Object> reverseList = new ArrayList<Object>(list);
// Reverse the order of its elements
Collections.reverse(reverseList);
// Now iteration will be in "latest added first" order - ie LIFO
for (Object o : reverseList) {
// Do something with o
}
I think that you're expecting your code to change the original list, but this is a wrong assumption since the code simply gets an object held by the list and doesn't remove it. Then you discard the object held by o, so there is no way to test if your method is working or not. To solve this, you've got to save the stuff produced from your method to test if it works or not.
int i = 5;
List savedJunk = new ArrayList();
while(i > 0) {
Object o = list.get(list.size() - i);
savedJunk.add(o);
i--;
}
for (Object foo : savedJunk) {
System.out.println(foo);
}
It's a good question and you pretty much had the right answer. The central idea is that items in a list appear in the order in which you added them, so to get the most recent item you need to go through the list in reverse. Here is one way to do that with a for loop.
ArrayList<String> myList = new ArrayList<String>();
myList.add("one");
myList.add("two");
myList.add("three");
myList.add("four");
for (int index = myList.size() - 1; index >= 0 ; index--) {
System.out.println(myList.get(index));
}
The output of the above code is:
four
three
two
one

Get objects' index in a Java List

I have a list of strings in my (Android) Java program, and I need to get the index of an object in the list. The problem is, I can only find documentation on how to find the first and last index of an object. What if I have 3 or more of the same object in my list? How can I find every index?
Thanks!
You need to do a brute force search:
static <T> List<Integer> indexesOf(List<T> source, T target)
{
final List<Integer> indexes = new ArrayList<Integer>();
for (int i = 0; i < source.size(); i++) {
if (source.get(i).equals(target)) { indexes.add(i); }
}
return indexes;
}
Note that this is not necessarily the most efficient approach. Depending on the context and the types/sizes of lists, you might need to do some serious optimizations. The point is, if you need every index (and know nothing about the structure of the list contents), then you need to do a deathmarch through every item for at best O(n) cost.
Depending on the type of the underlying list, get(i) may be O(1) (ArrayList) or O(n) (LinkedList), so this COULD blow up to a O(n2) implementation. You could copy to an ArrayList, or you could walk the LinkedList incrementing an index counter manually.
If documentation is not helping me in my logic in this situation i would have gone for a raw approach for Traversing the list in a loop and saving the index where i found a match
ArrayList<String> obj = new ArrayList<String>();
obj.add("Test Data"): // fill the list with your data
String dataToFind = "Hello";
ArrayList<Integer> intArray = new ArrayList<Integer>();
for(int i = 0 ; i<obj.size() ; i++)
{
if(obj.get(i).equals(dataToFind)) intArray.add(i);
}
now intArray would have contained all the index of matched element in the list
An alternative brute force approach that will also find all null indexes:
static List<Integer> indexesOf(List<?> list, Object target) {
final List<Integer> indexes = new ArrayList<Integer>();
int offset = 0;
for (int i = list.indexOf(target); i != -1; i = list.indexOf(target)) {
indexes.add(i + offset);
list = list.subList(i + 1, list.size());
offset += i + 1;
}
return indexes;
}

Categories