A lot of the new features of Java 8 are geared towards allowing Java programmers to write code in a more functional style than has been possible with previous versions.
So with this in mind I'm wondering whether the Java8 SDK includes an immutable Collections library built in? If so, do you discuss it in your book? If not, do you discuss how you might easily be tripped up when writing functional style code with mutable Collections?
Java 8 doesn't provide a new immutable collection library. However, Java has "unmodifiable" collections, which is a bit different.
For example, in the code below the variable newNumbers is a read-only view over the set numbers:
Set<Integer> numbers = new HashSet<>();
Set<Integer> newNumbers = Collections.unmodifiableSet(numbers);
This means you won’t be able to add new elements through the newNumbers variable. However, an unmodifiable collection is just a wrapper over a modifiable collection. This means that you could still add elements by accessing the numbers variable!
In comparison, immutable collections guarantee that nothing can change the collection anymore, regarding how many variables are pointing to it.
We have a whole chapter dedicated to Functional Programming (currently chapter 11) where we discuss how you can get tripped up with mutation (one of the example involves lists). We also present the notation of immutable ("persistent") data structures. In addition in the next chapter where we compare Java 8 and Scala, we briefly discuss how Scala collections are immutable.
So I invite you to have a look :-) We are making additional updates to this chapter in the next couple of weeks to strengthen it with more examples. All feedback is welcome!
Speaking of unmodifiable collections, Java 8 has added unmodifiable support for NavigableSet and NavigableMap. Overall, the following methods were added:
- public static <T> NavigableSet<T> unmodifiableNavigableSet(NavigableSet<T> s)
- public static <K,V> NavigableMap<K,V> unmodifiableNavigableMap(NavigableMap<K,? extends V> m)
- public static <T> NavigableSet<T> synchronizedNavigableSet(NavigableSet<T> s)
- public static <K,V> NavigableMap<K,V> synchronizedNavigableMap(NavigableMap<K,V> m)
- public static <E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type)
- public static <E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s, Class<E> type)
- public static <K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K,V> m, Class<K> keyType, Class<V> valueType)
- public static <E> SortedSet<E> emptySortedSet()
- public static <E> NavigableSet<E> emptyNavigableSet()
- public static final <K,V> SortedMap<K,V> emptySortedMap()
- public static final <K,V> NavigableMap<K,V> emptyNavigableMap()
This is in addition to the emptyIterator(), emptyListIterator() and emptyEnumeration() already added in Java 7.