Grouping elements of a list into sublists (maybe by using guava)

Sure it is possible, and even easier with Guava 🙂 Use Multimaps.index(Iterable, Function): ImmutableListMultimap<E, E> indexed = Multimaps.index(list, groupFunction); If you give concrete use case it would be easier to show it in action. Example from docs: List<String> badGuys = Arrays.asList(“Inky”, “Blinky”, “Pinky”, “Pinky”, “Clyde”); Function<String, Integer> stringLengthFunction = …; Multimap<Integer, String> index = Multimaps.index(badGuys, … Read more

Identify groups of consecutive numbers in a list

EDIT 2: To answer the OP new requirement ranges = [] for key, group in groupby(enumerate(data), lambda (index, item): index – item): group = map(itemgetter(1), group) if len(group) > 1: ranges.append(xrange(group[0], group[-1])) else: ranges.append(group[0]) Output: [xrange(2, 5), xrange(12, 17), 20] You can replace xrange with range or any other custom class. Python docs have a … Read more

Java 8 is not maintaining the order while grouping

Not maintaining the order is a property of the Map that stores the result. If you need a specific Map behavior, you need to request a particular Map implementation. E.g. LinkedHashMap maintains the insertion order: groupedResult = people.collect(Collectors.groupingBy( p -> new GroupingKey(p, groupByColumns), LinkedHashMap::new, Collectors.mapping((Map<String, Object> p) -> p, toList()))); By the way, there is … Read more

Grouping by week/month/etc & ActiveRecord?

In Postgres you can do: @user.comments.group(“DATE_TRUNC(‘month’, created_at)”).count to get: {“2012-08-01 00:00:00″=>152, “2012-07-01 00:00:00″=>57, “2012-09-01 00:00:00″=>132} It accepts values from “microseconds” to “millennium” for grouping: http://www.postgresql.org/docs/8.1/static/functions-datetime.html#FUNCTIONS-DATETIME-TRUNC

Stream groupingBy: reducing to first element of list [duplicate]

Actually, you need to use Collectors.toMap here instead of Collectors.groupingBy: Map<String, Valuta> map = getValute().stream() .collect(Collectors.toMap(Valuta::getCodice, Function.identity())); groupingBy is used to group elements of a Stream based on a grouping function. 2 Stream elements that will have the same result with the grouping function will be collected into a List by default. toMap will collect … Read more

tech