Skip to content

Tag: collections

Get index of element that matches a predicate

I know how to find the first element of a list by predicate: Find first element by predicate Is there an easy way to get the index of that element? Answer If I understood correctly, that’s the classic case where you need IntStream; but that would only apply for a List obviously.

detect last foreach loop iteration

Supposing that I have some foreach loop like this: Is there a way to check inside foreach that the actual name is the last one in Set without a counter? I didn’t found here some question like this. Answer There isn’t, take a look at How does the Java ‘for each’ loop work? You must chan…

Java Vowel count using Collection

I am asked to write a code to count and display vowels in a String using Sets. Any suggestions as to why the code below gives wrong output? Switch seemed like the obvious approach, I also tried with an if-statemen, but neither work properly. Answer I’m pretty sure it’s partially because you’…

List.of() or Collections.emptyList()

As an special case of List.of(…) or Collections.unmodifiableList() – what is the preferred Java 9 way of pointing to an empty and immutable list? Keep writing or switch to Answer What is the preferred Java 9 way of pointing to an empty and immutable list? The difference is rather subtle so “…

Merge Map<String, List Java 8 Stream

I would like to merge two Map with JAVA 8 Stream: I try to use this implementation: However, this implementation only create a result like: Map<String, List<Object>> If one key is not contained in the mapGlobal, it would be added as a new key with the corresponding List of String. If the key is du…

Java collection like c# KeyedColllection

Is there a Java collection that has the same behavior as the c# abstract KeyedCollection class (that is items can be retrieved by both key and index)? I have looked around but can’t find anything similar. Thanks, Nick Answer I think you can develop Your own class by extending a HashMap