why HashMap Values are not cast in List?

TL;DR List<V> al = new ArrayList<V>(hashMapVar.values()); Explanation Because HashMap#values() returns a java.util.Collection<V> and you can’t cast a Collection into an ArrayList, thus you get ClassCastException. I’d suggest using ArrayList(Collection<? extends V>) constructor. This constructor accepts an object which implements Collection<? extends V> as an argument. You won’t get ClassCastException when you pass the result of … Read more

ConcurrentModificationException for ArrayList [duplicate]

You can’t remove from list if you’re browsing it with “for each” loop. You can use Iterator. Replace: for (DrugStrength aDrugStrength : aDrugStrengthList) { if (!aDrugStrength.isValidDrugDescription()) { aDrugStrengthList.remove(aDrugStrength); } } With: for (Iterator<DrugStrength> it = aDrugStrengthList.iterator(); it.hasNext(); ) { DrugStrength aDrugStrength = it.next(); if (!aDrugStrength.isValidDrugDescription()) { it.remove(); } }

What is the fastest Java collection with the basic functionality of a Queue?

ArrayDeque is best. See this benchmark, which comes from this blog post about the results of benchmarking this. ArrayDeque doesn’t have the overhead of node allocations that LinkedList does nor the overhead of shifting the array contents left on remove that ArrayList has. In the benchmark, it performs about 3x as well as LinkedList for … Read more

What is the purpose of collections.ChainMap?

[*] I like @b4hand’s examples, and indeed I have used in the past ChainMap-like structures (but not ChainMap itself) for the two purposes he mentions: multi-layered configuration overrides, and variable stack/scope emulation. I’d like to point out two other motivations/advantages/differences of ChainMap, compared to using a dict-update loop, thus only storing the “final” version”: More … Read more

What is the best way to combine two lists into a map (Java)?

Been a while since this question was asked but these days I’m partial to something like: public static <K, V> Map<K, V> zipToMap(List<K> keys, List<V> values) { return IntStream.range(0, keys.size()).boxed() .collect(Collectors.toMap(keys::get, values::get)); } For those unfamiliar with streams, what this does is gets an IntStream from 0 to the length, then boxes it, making it … Read more

Checking if a collection is empty in Java: which is the best method?

You should absolutely use isEmpty(). Computing the size() of an arbitrary list could be expensive. Even validating whether it has any elements can be expensive, of course, but there’s no optimization for size() which can’t also make isEmpty() faster, whereas the reverse is not the case. For example, suppose you had a linked list structure … Read more

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