Java performance avoid creating new in loop - java

I have a code like this
Map<String, List> searchMap = new HashMap<String, List>();
for(int i=0; i<something.size(); i++){
List<String> list = new ArrayList<String>();
list = getResult(...);
...
searchMap.put(differentkey, list);
}
Each time I am creating new List in loop. How to avoid creating new list in loop.

Simply don't create the List at all since it is not even used in the code you have shown.
List<String> list = getResult(...);

Why would you want to? It looks like you want as many lists as you have keys, given that your map is from a key to a list... so you want that many distinct lists.
In particular, you don't want to just clear the list on each iteration - as otherwise each map entry will refer to the same list.
Now you don't have to create an empty list which you then ignore - you can assign the value of getResult() immediately to the variable, in the declaration:
List<String> list = getResult(...);
That's likely to still be creating a new list on each iteration (unless getResult() returns an existing one) but that's probably what you want anyway.
Note that there's no benefit in declaring the list variable outside the loop - the variable declaration doesn't affect performance, but it's generally a good idea to limit a variable's scope as much as possible - so I'd keep the declaration where it is.

Try this instead:
Map<String, List> searchMap = new HashMap<String, List>();
for(int i=0; i<something.size(); i++){
List<String> list = getResult(...);
...
searchMap.put(differentkey, list);
}
There's no need to construct a new list.

Map<String, List> searchMap = new HashMap<String, List>();
List<String> list = new ArrayList<String>();
for(int i=0; i<something.size(); i++){
list = getResult(...);
...
searchMap.put(differentkey, list);
}
On the 4th line (list = getResult(...);) you're assigning a new object to your listvariable. So there's no need to create new list before that. Your variable will be replaced anyway.

for(int i=0; i<something.size(); i++){
List<String> list = new ArrayList<String>();
list = getResult(...);
is equivalent to
for(int i=0; i<something.size(); i++){
List<String> list = getResult(...);
But I'm not sure, whether you're really searching for this.

Related

Comparing two ArrayLists and remove duplicates from original ArrayList

I have two Custom Arraylist:
List<Item> before = new ArrayList<Item>();
List<ItemEx> after = new ArrayList<ItemEx>();
before.add(new Item(1L,"test1"));
before.add(new Item(2L,"test2"));
before.add(new Item(3L,"test3"));
after.add(new ItemEx(1L,"test4"));
after.add(new ItemEx(2L,"test5"));
after.add(new ItemEx(4L,"test6"));
after.add(new ItemEx(5L,"test7"));
I want to store the elements in the List<ItemEx> after and the element shoulds be after the removing of common element is {3L, 4L, 5L}.
FYI
List<Item> & List<ItemEx> should be SAME TYPE .
Logic
List<String> before = new ArrayList<String>();
List<String> after = new ArrayList<String>();
List<String> list_checking = new ArrayList<String>(before);
list_checking.addAll(after);
List<String> list_common = new ArrayList<String>(before);
list_common.retainAll(after);
list_checking.removeAll(list_common);
Try this :
HashSet hs = new HashSet();
hs.addAll(before);
hs.addAll(after);
after.clear();
after.addAll(hs);
Now, in after list you get desire values.
Its simple. Take a copy of the existing one into a temporary Variable if you want for future use.
ArrayList temporiginalArrList=OriginalArrayList;
//here 'T' can be a specific object to want to save
OriginalArrayList.removeAll(secondArrayList);

Complex Hashmap ArrayList Generator

Here's some code:
ArrayList<String> List = new ArrayList<>();
Map<String, List<String> > map = new HashMap<String, List<String>>();
List.add("stringA");
List.add("stringB");
List.add("stringC");
for(int i = 0; i<List.size();i++){
String key = List.get(i);
List<String> value = new ArrayList<String>();
map.put(key, value);
}
This code takes whatever is in the ArrayList, loops through it, adds it to the Map, and then creates an empty ArrayList with each string name as the variable name. Now, this works, but there's one problem, unless I'm overlooking something. At some point, I will need to access the new empty ArrayLists that are in the map. However, I won't know what the titles of these ArrayLists are, without printing them out, which I don't want to do. Basically, I'm thinking I need a map method or class and then an additional map key method or class. I'm not sure how to implement it but maybe something like this:
public class MapKey {
public MapKey(int count, String header){
}
}
Map<MapKey, List<String> > map = new HashMap<MapKey, List<String>>();
Another option I've considered is to somehow loop through the map array and add Strings to each ArrayList, but I'm very new to maps and looping through them. Especially ones that contain ArrayLists as their values.
There're multiple ways to access keys and values of your HashMap:
for (Map.Entry<String,ArrayList<String>> entry : map.entrySet()) {
String key = entry.getKey();
ArrayList<String> value = entry.getValue();
// do your work
}
or
Set<String> keys = map.keySet();
for(String key : keys){
ArrayList<String> value = map.get(key);
}
Read the java HashMap api Java HashMap Link
Edit:
you dont need to loop through your outside ArrayList objects when you add all of its elements to another, just simply invoke addAll(), it will append all elements of an arraylist to another.
ArrayList<String> aList = map.get("stringA");
assume your first outside ArrayList is called outListOne;
aList.addAll(outListOne);
Appends to corresponding lists:
//assume number of outside lists are equal to number of map elements
String[] keysArr = {"stringA", "stringB", "stringC"};
ArrayList[] outLists = {outListOne, outListTwo, outListThree};
// adds outside lists to corresponding map ArrayList lists
for(int i = 0; i < keysArr.length; i++){
list = map.get(keysArr[i]); // you ArrayList in a map, get it by key name
list.addAll(outLists[i]); // append elements from out list to corresponding list
}
Not exactly sure what you mean by "titles of these ArrayLists." But here are a few code snippets that might give you a better idea of how to work with your map:
// add string x to the list for "stringA"
map.get("stringA").add(x);
// print all the values in the list for "stringC"
for (String s: map.get("stringC")) {
System.out.println(s);
}
// print the names of the lists that contain "xyzzy"
for (String key: map.keySet()) {
if (map.get(key).contains("xyzzy")) {
System.out.println(key);
}
}
// remove "foo" wherever it appears in any of the lists
for (List<String> list: map.values()) {
while (list.remove("foo")){}
}

Copying arraylist

I think doing arraylist1=arraylist2 makes the 2 of them share the same memory. How can I copy an arraylist without them doing that? I want to treat them sepparately.
List<Integer> rez = new ArrayList<>();
List<Integer> rezc = new ArrayList<>();
rez.add(1);
rezc=rez;
rezc.add(2);
for (int s : rez) {
System.out.print(s + " ");
}//this will print 1 2
I think doing arraylist1=arraylist2 makes the 2 of them share the same memory.
Not quite, it makes both of those references refer to the same, single, object.
How can I copy an arraylist without them doing that?
Lots of options:
ArrayList has a copy constructor:
List<Integer> rezc = new ArrayList<>(rez);
List has an addAll method:
List<Integer> rezc = new ArrayList<>();
rezc.addAll(rez);
ArrayList has a clone method, but it's a bit ugly to use if rez is declared as a List because you have to assume it's an ArrayList and cast it, which is probably not a great idea:
List<Integer> rezc = (List<Integer>)((ArrayList<Integer>)rez).clone();
It's well worth reading through the JavaDoc when trying to figure things like this out.
The statement arraylist1=arraylist2 means they are referring to same ArrayList object. Reference variables arraylist1 and arraylist2 are referring to same object and hence, the changes done by arraylist1 will be seen when you are trying to access the object by arraylist2
If you want to make a new ArrayList then, ArrayList rezc = new ArrayList(rez)
Instead of this line rezc=rez;
Use List<Integer> rezc = new ArrayList<>(rez);
The long hand way is a for loop to cycle though one list while adding all the items to the second. Something like
for (int I = 0; I < rez.size() I++) {
rezc.add(rez.get(I)); }
But the previous answers are much more efficient.
If I understand correctly you are talking about Java shallow cloning v/s deep cloning. In this case the below code might help
List<Integer> rez = new ArrayList<>();
List<Integer> rezc = new ArrayList<>();
rez.add(1);
rezc.addAll(rez); // addAll
List<Integer> rezc2 = (List<Integer>)((ArrayList<Integer>)rez).clone(); //clone

how to solve this hashmap logical error in android?

I'm facing some known solvable problem but struck out here. In my code, the values are getting stored in ArrayList on the first for loop execution. However, on the 2nd loop and further, the values are overwritten by the final values in the ArrayList. Finally, the lastly entered values are alone getting stored with the number of times of size of the list.
lstall = (ListView)findViewById(R.id.lvall);
sampleArrayList = new ArrayList<HashMap<String, String>>();
ListAdapter sampleListAdapter;
dh = new DBHelper(this);
HashMap<String, String> sampleObjectMap;
List<String> lvall = dh.selectAll();
sampleObjectMap= new HashMap<String, String>();
for(int i=0;i<lvall.size();i++)
{
for (#SuppressWarnings("unused") String sampleObj : lvall)
{
sampleObjectMap.put("title", dh.val1(i));
sampleObjectMap.put("person", dh.pers(i));
sampleObjectMap.put("priorty", setpriority(String.valueOf(dh.prioirty(i))));
sampleObjectMap.put("dat", getDate(Long.valueOf(dh.time(i)),"dd/MM/yyyy"));
}
sampleArrayList.add(sampleObjectMap);
}
I need to store all the values in a arraylist and display within a list view. Any help is highly appreciated and thanks in advance.
You're creating a single HashMap<String, String> and repeatedly overwriting the entries within it.
In fact, you're doing that twice as you have a nested for loop for no obvious reason. I believe you want:
for (int i = 0; i < lvall.size(); i++)
{
HashMap<String, String> sampleObjectMap = new HashMap<String, String>();
sampleObjectMap.put("title", dh.val1(i));
sampleObjectMap.put("person", dh.pers(i));
sampleObjectMap.put("priorty", setpriority(String.valueOf(dh.prioirty(i))));
sampleObjectMap.put("dat", getDate(Long.valueOf(dh.time(i)),"dd/MM/yyyy"));
sampleArrayList.add(sampleObjectMap);
}
It also seems odd to use a list's size but not actually use the values within the list... you might want to consider restructuring your code...
Try it out:
for(int i=0;i<lvall.size();i++)
{
sampleObjectMap= new HashMap<String, String>();
sampleObjectMap.put("title", dh.val1(i));
sampleObjectMap.put("person", dh.pers(i));
sampleObjectMap.put("priorty", setpriority(String.valueOf(dh.prioirty(i))));
sampleObjectMap.put("dat", getDate(Long.valueOf(dh.time(i)),"dd/MM/yyyy"));
sampleArrayList.add(sampleObjectMap);
}
All the elements in the list have the reference of the same Map instance and you are overriding the same Map entries for each iteration.
for(int i=0;i<lvall.size();i++) {
// move it inside the loop
sampleObjectMap= new HashMap<String, String>();
But i don't think that you need a Map here. Just create a class with all the required fields as member variables.
I have not tested it, but try to create new Map
sampleObjectMap = new HashMap<String, String>();
in your inner loop, before you do put. Test it. Later try to use 1 map object and calling clear() after the map is recorded in the sampleArrayList.

insert array into an array

In my android application i need to insert an array into an array and access its values.
Is there any way that i can get this done.
Please share your valuable suggestions
Thanks in advance :)
So what's the issue?
Give this a try:
ArrayList<ClassName> l1 = new ArrayList<ClassName> ();
Now suppose you have array objects arr1 and arr2. You can add them to an ArrayList with the following:
l1.add(arr1);
l1.add(arr2);
Now you can access each element in l1 with
for(int i=0; i < l1.size;i++){
<ClassName> obj = l1.get(i);
// and do what you want to do
}
You are basically making a list of lists. Create a new list then add that list to the master list. Use generics so you don't have to do a lot of casting.
List<Object> listOfObjects = new ArrayList<Object>();
listOfObjects.add(obj1);
listOfObjects.add(obj2);
List<List<Object>> listOfLists = new ArrayList<List<Object>>();
listOfLists.add(listOfObjects);
// get first object in first list
listOfLists.get(0).get(0);
// add to the first list
listOfLists.get(0).add(0);
Here a example, but for It is for C#
ArrayList MainArray = new ArrayList();
MainArray.Add(new ArrayList());
MainArray.Add(new ArrayList());
MainArray.Add(new ArrayList());
(MainArray[1] as ArrayList).Add("Hello");
Response.Write((MainArray[1] as ArrayList)[0].ToString());
String myArray[] = new int[10];
for(int i=0; i<myArray.length(); i++) {
myArray[i] =value adding here;
}

Categories