Java: Get first item from a collection

Looks like that is the best way to do it: String first = strs.iterator().next(); Great question… At first, it seems like an oversight for the Collection interface. Note that “first” won’t always return the first thing you put in the collection, and may only make sense for ordered collections. Maybe that is why there isn’t … Read more

Java – How to create new Entry (key, value)

There’s public static class AbstractMap.SimpleEntry<K,V>. Don’t let the Abstract part of the name mislead you: it is in fact NOT an abstract class (but its top-level AbstractMap is). The fact that it’s a static nested class means that you DON’T need an enclosing AbstractMap instance to instantiate it, so something like this compiles fine: Map.Entry<String,Integer> … Read more

How to easily initialize a list of Tuples?

c# 7.0 lets you do this: var tupleList = new List<(int, string)> { (1, “cow”), (5, “chickens”), (1, “airplane”) }; If you don’t need a List, but just an array, you can do: var tupleList = new(int, string)[] { (1, “cow”), (5, “chickens”), (1, “airplane”) }; And if you don’t like “Item1” and “Item2”, you … Read more

Java Ordered Map

The SortedMap interface (with the implementation TreeMap) should be your friend. The interface has the methods: keySet() which returns a set of the keys in ascending order values() which returns a collection of all values in the ascending order of the corresponding keys So this interface fulfills exactly your requirements. However, the keys must have … Read more

How to quickly and conveniently create a one element arraylist [duplicate]

Fixed size List The easiest way, that I know of, is to create a fixed-size single element List with Arrays.asList(T…) like // Returns a List backed by a varargs T. return Arrays.asList(s); Variable size List If it needs vary in size you can construct an ArrayList and the fixed-sizeList like return new ArrayList<String>(Arrays.asList(s)); and (in … Read more

Getting an element from a Set

To answer the precise question “Why doesn’t Set provide an operation to get an element that equals another element?”, the answer would be: because the designers of the collection framework were not very forward looking. They didn’t anticipate your very legitimate use case, naively tried to “model the mathematical set abstraction” (from the javadoc) and … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)