Recreating a Dictionary from an IEnumerable

I have a method that returns an IEnumerable<KeyValuePair<string, ArrayList>>, but some of the callers require the result of the method to be a dictionary. How can I convert the IEnumerable<KeyValuePair<string, ArrayList>> into a Dictionary<string, ArrayList> so that I can use TryGetValue? method: public IEnumerable<KeyValuePair<string, ArrayList>> GetComponents() { // … yield return new KeyValuePair<string, ArrayList>(t.Name, controlInformation); … Read more

What Java 8 Stream.collect equivalents are available in the standard Kotlin library?

In Java 8, there is Stream.collect which allows aggregations on collections. In Kotlin, this does not exist in the same way, other than maybe as a collection of extension functions in the stdlib. But it isn’t clear what the equivalences are for different use cases. For example, at the top of the JavaDoc for Collectors … Read more

Properly removing an Integer from a List

Here’s a nice pitfall I just encountered. Consider a list of integers: List<Integer> list = new ArrayList<Integer>(); list.add(5); list.add(6); list.add(7); list.add(1); Any educated guess on what happens when you execute list.remove(1)? What about list.remove(new Integer(1))? This can cause some nasty bugs. What is the proper way to differentiate between remove(int index), which removes an element … Read more

Which is more efficient, a for-each loop, or an iterator?

Which is the most efficient way to traverse a collection? List<Integer> a = new ArrayList<Integer>(); for (Integer integer : a) { integer.toString(); } or List<Integer> a = new ArrayList<Integer>(); for (Iterator iterator = a.iterator(); iterator.hasNext();) { Integer integer = (Integer) iterator.next(); integer.toString(); } Please note, that this is not an exact duplicate of this, this, … Read more