Java


26
Jun 11

Reducing the size of List in Java

I had a List that had around 70000 objects in it and I needed only the first 15000. I was about to create a new empty array list and iterate 15000 times over the current one in order to get a smaller list. That would have been a mess.

I searched a bit and realized there was an easier (and I’m hoping it’s more efficient) way to reduce the size of a list.

//templist has 70000 objects in it

tempList.subList(15000 – 1, tempList.size()-1).clear();

//templist now has the first 15000 objects in it

//15000 – 1 because the positions start from 0

 


22
Jun 11

Fetch Multiple Objects by key in JDO using getObjectsById

On Google Appengine I needed to fetch multiple objects, the key to which is present with me. I tried using PersistenceManager#getObjectsById(Collection) method and passed a list of keys to it. But that threw an exception. On further probing I realized this is not how #getObjectsById works.

There might be other ways of doing it but this is how I’ve done it :

List list = new ArrayList();

for(Key key : <iterate-over-list-of-keys>){

list.add(persistenceManager.newObjectIdInstance(<class-name-here>, key));

}

Collection objects = persistenceManager.getObjectsById(list);

Hopefully this helps you use the getObjectsById method in JDO on google appengine.


3
Apr 11

Convert json string to Map in Java using Gson

I’ve been using Gson from quite some time now. It’s a Java library developed by Google that is used to convert JSON to Java objects and vice versa. You can read more about Gson here.

I came across this json string which I had to convert into a Map. Here’s how you do it:

Type type =
 new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> map =
 gson.fromJson("{'key1':'123','key2':'456'}", type);

Hope that helps you convert a json string into a java Map.