Array to Collection: Optimized code

What do you mean by better way: more readable: List<String> list = new ArrayList<String>(Arrays.asList(array)); less memory consumption, and maybe faster (but definitely not thread safe): public static List<String> toList(String[] array) { if (array==null) { return new ArrayList(0); } else { int size = array.length; List<String> list = new ArrayList(size); for(int i = 0; i < … Read more

List.AsReadOnly() vs IReadOnlyCollection

If you just return an actual List<T> as an IReadOnlyList<T>, then the caller can always just cast it back, and then modify the list as they please. Conversely, calling AsReadOnly() creates a read-only wrapper of the list, which consumers can’t update. Note that the read-only wrapper will reflect changes made to the underlying list, so … Read more

How does ConcurrentHashMap work internally?

I would read the source of ConcurrentHashMap as it is rather complicated in the detail. In short it has Multiple partitions which can be locked independently. (16 by default) Using concurrent Locks operations for thread safety instead of synchronized. Has thread safe Iterators. synchronizedCollection’s iterators are not thread safe. Does not expose the internal locks. … Read more

Sort a Java collection object based on one field in it

here is my “1liner”: Collections.sort(agentDtoList, new Comparator<AgentSummaryDTO>(){ public int compare(AgentSummaryDTO o1, AgentSummaryDTO o2){ return o1.getCustomerCount() – o2.getCustomerCount(); } }); UPDATE for Java 8: For int datatype Collections.sort(agentDtoList, (o1, o2) -> o1.getCustomerCount() – o2.getCustomerCount()); or even: Collections.sort(agentDtoList, Comparator.comparing(AgentSummaryDTO::getCustomerCount)); For String datatype (as in comment) Collections.sort(list, (o1, o2) -> (o1.getAgentName().compareTo(o2.getAgentName()))); ..it expects getter AgentSummaryDTO.getCustomerCount()

.collect with an index

Since Groovy 2.4.0 there is a withIndex() method which gets added to java.lang.Iterable. So, in a functional fashion (no side effect, immutable), it looks like def myList = [ [position: 0, name: ‘Bob’], [position: 0, name: ‘John’], [position: 0, name: ‘Alex’], ] def result = myList.withIndex().collect { element, index -> [position: index, name: element[“name”]] }

Determine if collection is of type IEnumerable

If you mean the collection, then just as: var asEnumerable = i as IEnumerable<int>; if(asEnumerable != null) { … } However, I’m assuming (from the example) that you have a Type: The object will never be “of” type IEnumerable<int> – but it might implement it; I would expect that: if(typeof(IEnumerable<int>).IsAssignableFrom(type)) {…} would do. If you … Read more

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