Skip to content

Commit

Permalink
Fix #66: RoqCollection by and group helpers
Browse files Browse the repository at this point in the history
  • Loading branch information
melloware committed Sep 21, 2024
1 parent bf29d0d commit 5362e42
Showing 1 changed file with 49 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
package io.quarkiverse.roq.frontmatter.runtime;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class RoqCollection extends ArrayList<Page> {

Expand All @@ -27,6 +32,49 @@ public List<Page> paginated(Paginator paginator) {
return this.subList(zeroBasedCurrent * paginator.limit, Math.min(this.size(), zeroBasedCurrent + paginator.limit));
}

/**
* Retrieves a list of non-null values from the pages for the specified keys.
* This method searches through all the pages for each of the provided keys and
* collects all non-null values associated with the keys.
*
* @param keys the keys to search for in the pages' data. Multiple keys can be passed.
* @return a {@code List<Object>} containing all non-null values found in the pages for the specified keys.
*/
public List<Object> by(String... keys) {
return this.stream()
.flatMap(page -> Arrays.stream(keys)
.map(page::data) // Get the data for each key
.filter(Objects::nonNull) // Filter out null results
)
.collect(Collectors.toList()); // Collect non-null values into a list
}

/**
* Groups the pages by the values found for the specified keys.
* For each key provided, this method searches through the pages and groups them
* based on the values associated with that key. The resulting map will contain the
* found values as keys and the corresponding list of pages that contain those values.
*
* @param keys the keys to group pages by. Multiple keys can be passed.
* @return a {@code Map<Object, List<Page>>} where each key is a unique value found
* in the pages' data for the specified keys, and the corresponding value is
* a list of pages where the value was found.
*/
public Map<Object, List<Page>> group(String... keys) {
Map<Object, List<Page>> resultMap = new LinkedHashMap<>();

for (Page page : this) {
for (String key : keys) {
Object value = page.data(key);
if (value != null) {
resultMap.computeIfAbsent(value, k -> new ArrayList<>()).add(page);
}
}
}

return resultMap;
}

public record Paginator(
String collection,
int collectionSize,
Expand Down Expand Up @@ -55,4 +103,4 @@ public boolean isSecond() {
}
}

}
}

0 comments on commit 5362e42

Please sign in to comment.