What is the difference between using a List<Map<String, String>>
vs List<Object>
in terms of usage and performance.
Suppose I have to create a list of map having only 3 types of key value pair, I can instead create an Object having only 3 properties and make a list of objects.
The question here is out of the two approaches which one should be used in which scenario?
As objects, in a class, you can call methods on string objects using the . methodName() notation. The string class is available by default in python, so you do not need an import statement to use the object interface to strings. Lists are objects too.
Read carefully, the List<?> means you can assign any type of List to it and List<Object> means you can store any type of object into it.
Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList); Any Collection can be passed as an argument to the constructor as long as its type extends the type of the ArrayList , as String extends Object .
Lets first clarify what we are talking about: it is
List<Map<String, String>>
versus
List<Foo>
where Foo objects have a number of "properties", that would be stored in a map (as key value pairs) with option one.
In that case, you absolutely go for option two. Simply because good OOP is about creating helpful abstractions, aka models. Meaning: when you have attributes that belong together, then using a class to wrap around them is the natural way to go.
That gives you slight advantages on performance (because you avoid the map access), but the core thing is: it allows you to write compile time checked code. You see:
int foo = list.get(0).map.get("key");
can fail at runtime - you don't know if map contains that key, and if that is an Integer.
But
int foo = list.get(0).getFoo(); // resp. ...get(0).fieldName
can be checked by the compiler! (yes, those get() calls can still fail at runtime, but that is something you don't get around anyway)
Beyond that: do not worry about performance on this level: first of all, you have to understand what really affects your performance when writing Java code. Because you absolutely want to avoid that "this code is ugly but might give better performance" thoughts sneak into your design. Focus on writing clean code that gets the job done in a straight forward way. Do never write less expressive code because you assume it is faster. When you have a performance problem - profile your code, identify the root cause and fix that.
But do not allow for premature optimization thoughts to impact the quality of your code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With