Elegant way of counting occurrences in a java collection

Now let’s try some Java 8 code: static public Map<String, Integer> toMap(List<String> lst) { return lst.stream() .collect(HashMap<String, Integer>::new, (map, str) -> { if (!map.containsKey(str)) { map.put(str, 1); } else { map.put(str, map.get(str) + 1); } }, HashMap<String, Integer>::putAll); } static public Map<String, Integer> toMap(List<String> lst) { return lst.stream().collect(Collectors.groupingBy(s -> s, Collectors.counting())); } I think this … Read more

How to create ArrayList (ArrayList) from array (int[]) in Java

The problem in intList = new ArrayList<Integer>(Arrays.asList(intArray)); is that int[] is considered as a single Object instance since a primitive array extends from Object. This would work if you have Integer[] instead of int[] since now you’re sending an array of Object. Integer[] intArray = new Integer[] { 0, 1 }; //now you’re sending a … Read more

ArrayList takes String

But how can we add strings to arraylist whose type has already been specified as Integer? Because of the way Java generics was designed for backwards compatibility, with type erasure and raw types, basically. At execution time, there’s no such things as an ArrayList<Integer> – there’s just an ArrayList. You’re using the raw type List, … Read more

java.math.BigInteger cannot be cast to java.lang.Long

Better option is use SQLQuery#addScalar than casting to Long or BigDecimal. Here is modified query that returns count column as Long Query query = session .createSQLQuery(“SELECT COUNT(*) as count FROM SpyPath WHERE DATE(time)>=DATE_SUB(CURDATE(),INTERVAL 6 DAY) GROUP BY DATE(time) ORDER BY time;”) .addScalar(“count”, LongType.INSTANCE); Then List<Long> result = query.list(); //No ClassCastException here Related link Hibernate javadocs … Read more

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