Collections.synchronizedList and synchronized

You don’t need to synchronize as you put in your example. HOWEVER, very important, you need to synchronize around the list when you iterate it (as noted in the Javadoc): It is imperative that the user manually synchronize on the returned list when iterating over it: List list = Collections.synchronizedList(new ArrayList()); … synchronized(list) { Iterator … Read more

Flattening a collection

Using Java 8 and if you prefer not to instantiate a List instance by yourself, like in the suggested (and accepted) solution someMap.values().forEach(someList::addAll); You could do it all by streaming with this statement: List<String> someList = map.values().stream().flatMap(c -> c.stream()).collect(Collectors.toList()); By the way it should be interesting to know, that on Java 8 the accepted version … Read more

best way to pick a random subset from a collection?

Jon Bentley discusses this in either ‘Programming Pearls’ or ‘More Programming Pearls’. You need to be careful with your N of M selection process, but I think the code shown works correctly. Rather than randomly shuffle all the items, you can do the random shuffle only shuffling the first N positions – which is a … Read more

Why we can’t do List mylist = ArrayList(); [duplicate]

Suppose we could. Then this program would have to be fine: ArrayList<Banana> bananas = new ArrayList<Banana>(); List<Fruit> fruit = bananas; fruit.add(new Apple()); Banana banana = bananas.get(0); That’s clearly not type safe – you’ve ended up with an apple in the collection of bananas. What you can do is: List<? extends Fruit> fruit = new ArrayList<Banana>(); … Read more

Auto-initializing C# lists

In addition to the functional solutions provided (using the static methods on the Enumerable class), you can pass an array of doubles in the constructor. var tenDoubles = new List<double>(new double[10]); This works because the default value of an double is already 0, and probably performs slightly better.

Scala: Remove duplicates in list of objects

list.groupBy(_.property).map(_._2.head) Explanation: The groupBy method accepts a function that converts an element to a key for grouping. _.property is just shorthand for elem: Object => elem.property (the compiler generates a unique name, something like x$1). So now we have a map Map[Property, List[Object]]. A Map[K,V] extends Traversable[(K,V)]. So it can be traversed like a list, … Read more

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