Sat Dec 29 06:02:41 PST 2018


Hello guys, this is my first article in Java 9 features on this blog and today you'll learn about my favorite feature
"factory methods for collection", which is introduced as part of JEP 269. The JEP stands for JDK enhancement proposal. If you have worked in
Groovy or
Kotlin then you know that how easy is to create the list with elements using collection literals e.g. to create a list of 1, 2, 3 you can simply write
val items = listOf(1, 2, 3). Unfortunately, Java doesn't support that yet but things have been improved with the factory methods for collection in JDK 9 and it's almost like that. JDK has added
static factory methods like
of() on to basic Collection interfaces which you can use to create a list of items.







One of the common problem while removing elements from an ArrayList in Java is the ConcurrentModificationException. If you use classical for loop with the index or enhanced for loop and try to remove an element from the ArrayList using
remove() method, you will get the
ConcurrentModificationException but if you use Iterator's remove method or ListIterator's
remove() method, then you won't get this error and be able to remove the element. It's an unwritten rule in Java that while looping through the list, you should not
add() or
remove() elements until the collection supports
fail-safe Iterator e.g.
CopyOnWriteArrayList, which operate on a copy of list rather than the original list.








Map and List are two common data structures available in Java and in this article we will see how can we convert Map values or Map keys into List in Java. The primary difference between Map (HashMap, ConcurrentHashMap or TreeMap) and List is that Map holds two objects key and value while List just holds one object which itself is a value. Key in hashmap is just an addon to find values, so you can just pick the values from Map and create a List out of it. The map in Java allows duplicate value which is fine with List which also allows duplicates but Map doesn't allow duplicate key.






Comments

Popular posts from this blog

termux vnc viewer setup

../Settings.jpg

me.html