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 do I speed up counting rows in a PostgreSQL table?

For a very quick estimate: SELECT reltuples FROM pg_class WHERE relname=”my_table”; There are several caveats, though. For one, relname is not necessarily unique in pg_class. There can be multiple tables with the same relname in multiple schemas of the database. To be unambiguous: SELECT reltuples::bigint FROM pg_class WHERE oid = ‘my_schema.my_table’::regclass; If you do not … Read more

How to count number of element occurrences in a list in Prolog

The following is based on my previous answer to “Remove duplicates in list (Prolog)” and on this previous answer to the question “Prolog union for A U B U C”. list_item_subtracted_count0_count/5 is derived from list_item_subtracted/3. list_counts/2 is derived from list_setB/2, which were both defined here. list_item_subtracted_count0_count([], _, [], N,N). list_item_subtracted_count0_count([A|As], E, Bs1, N0,N) :- if_(A … Read more

mysql count into PHP variable

Like this: // Changed the query – there’s no need for DISTINCT // and aliased the count as “num” $data = mysql_query(‘SELECT COUNT(`users_id`) AS num FROM `users_table`’) or die(mysql_error()); // A COUNT query will always return 1 row // (unless it fails, in which case we die above) // Use fetch_assoc for a nice associative … Read more

Row count in a csv file

with open(adresse,”r”) as f: reader = csv.reader(f,delimiter = “,”) data = list(reader) row_count = len(data) You are trying to read the file twice, when the file pointer has already reached the end of file after saving the data list.

MongoDB ‘count()’ is very slow. How do we refine/work around with it?

There is now another optimization than create proper index. db.users.ensureIndex({name:1}); db.users.find({name:”Andrei”}).count(); If you need some counters i suggest to precalculate them whenever it possible. By using atomic $inc operation and not use count({}) at all. But mongodb guys working hard on mongodb, so, count({}) improvements they are planning in mongodb 2.1 according to jira bug.