public static void main(String[] args) { //Filter example Seq<Integer> seq = Seq.range(1, 5); seq.filter(number -> number < 3) .forEach(System.out::println); //Cycle // (1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2, ...) Seq.range(1, 4).cycle(3) .forEach(System.out::println); //groupBy // (tuple(1, (1, 3)), tuple(0, (2, 4))) Seq.range(1, 8).groupBy(i -> i % 2) .forEach((key,value)-> { System.out.println(key +", "+value); }); //join Seq.of(1, 2, 3,4).toString(", "); }
@Test public void testCustomComparatorPasses() throws JsonProcessingException { CustomComparators comparators = new DeterministicObjectMapper.CustomComparators(); comparators.addConverter(MyObject.class, Comparator.comparing(MyObject::getX)); ObjectMapper customizedComparatorsMapper = DeterministicObjectMapper.create(Json.serializer().mapper(), comparators); Set<MyObject> objects = Seq.of( new MyObject(2), new MyObject(4), new MyObject(3), new MyObject(1) ).toSet(); String actual = customizedComparatorsMapper.writer().writeValueAsString(objects); String expected = "[{\"x\":1},{\"x\":2},{\"x\":3},{\"x\":4}]"; assertEquals(expected, actual); }
private static PostMeta metaFromPost(PostRaw postRaw) { List<TagOrLibrary> tagOrLibraries = Lists.newArrayList(); tagOrLibraries.addAll(Seq.seq(postRaw.getJavaLibs()) .map(l -> new TagOrLibrary(l.getName(), TagOrLibrary.Type.Library, null)) .toList()); tagOrLibraries.addAll(Seq.seq(postRaw.getTags()) .map(t -> new TagOrLibrary(t.getName(), TagOrLibrary.Type.Tag, null)) .toList()); tagOrLibraries = Seq.seq(tagOrLibraries).sorted(e -> e.getName()).toList(); return PostMeta.builder() .postId(postRaw.getPostId()) .tagOrLibraries(tagOrLibraries) .dateCreated(postRaw.getDateCreated()) .title(postRaw.getTitle()) .slug(postRaw.getSlug()) .metaDesc(postRaw.getMetaDesc()) .build(); }
private static final List<HtmlCssTheme> fetchPopularThemes() { return Seq.seq(suppliers) .map(sup -> { /* * If one fails we don't want them all to fail. * This can be handled better but good enough for now. */ try { return sup.get(); } catch (Exception ex) { log.warn("Error fetching themes", ex); return Lists.<HtmlCssTheme>newArrayList(); } }) .flatMap(List::stream) .sorted(popularSort) .toList(); }
public static List<HtmlCssTheme> popularThemes() { HttpUrl url = HttpUrl.parse(POPULAR_THEMES_URL); Request request = new Request.Builder().url(url).get().build(); String html = Retry.retryUntilSuccessfulWithBackoff( () -> client.newCall(request).execute() ); Elements elements = Jsoup.parse(html).select("script"); Element script = Seq.seq(elements) .filter(e -> { return e.html().startsWith("window.INITIAL_STATE="); }) .findFirst().orElse(null); String rawJson = script.html().substring("window.INITIAL_STATE=".length()); JsonNode node = Json.serializer().nodeFromJson(rawJson); return Seq.seq(node.path("searchPage").path("results").path("matches")) .map(ThemeForestScraper::themeFromElement) .toList(); //.map(ThemeForestScraper::themeFromElement).toList(); }
public static List<HtmlCssTheme> popularThemes() { HttpUrl url = HttpUrl.parse(POPULAR_THEMES_URL); Request request = new Request.Builder().url(url).get().build(); // Retry if the request is not successful code >= 200 && code < 300 String html = Retry.retryUntilSuccessfulWithBackoff( () -> client.newCall(request).execute() ); // Select all the elements with the given CSS selector. Elements elements = Jsoup.parse(html).select("#themes .item"); List<HtmlCssTheme> themes = Seq.seq(elements) .map(WrapBootstrapScraper::themeFromElement) .toList(); return themes; }
@Override public boolean processLine(@Nonnull String line) throws IOException { final String[] strings = csvParser.parseLine(line); if (strings == null) { return false; } if (firstLine) { fieldNames = strings; firstLine = false; return true; } final Map<String, Object> fields = Seq.of(fieldNames) .zipWithIndex() .map(nameAndIndex -> nameAndIndex.map2(index -> strings[Math.toIntExact(index)])) .collect(Collectors.toMap(Tuple2::v1, Tuple2::v2)); fields.put(Message.FIELD_ID, new UUID().toString()); messages.add(new Message(fields)); return true; }
public String toCsvRecord() { // collapse points into a single string String points = Seq.seq(this.path) .map(p -> p.getLat() + Evaluator.DELIMITER_POINT + p.getLon()) .collect(Collectors.joining(Evaluator.DELIMITER_POINT_LIST)); Object[] vals = new Object[] { place.getId(), place.getLatitude(), place.getLongitude(), time, type, rank, value, distance, duration, temperature, heatIndex, costRouteTemperature, costRouteHeatIndex, points }; return Arrays.stream(vals).map(String::valueOf) .collect(Collectors.joining(Evaluator.DELIMITER)); }
static public List<SalonQuestion> getSalonQuestions(long docID, SalonDB salonDB) throws SQLException { String sql = "SELECT * from question where document_id = ?"; try (PreparedStatement stmt = salonDB.prep(sql)) { stmt.setLong(1, docID); Seq<SalonQuestion> docs = SQL.seq(stmt, Unchecked.function(rs -> { SalonQuestion salonq = new SalonQuestion(); salonq.questionID = rs.getLong("question_id"); salonq.assignmentID = rs.getLong("assignment_id"); salonq.questionText = rs.getString("question_text"); salonq.documentID = rs.getLong("document_id"); salonq.questionTitle = rs.getString("question_title"); salonq.createdDate = rs.getTimestamp("created_date"); salonq.userID = rs.getLong("user_id"); return salonq; } )); return docs.toList(); } }
public static void main(String[] args) { //Parallel Stream created using Seq Seq.of("I", "work", "for", "ION").parallel() .map(s -> s + " ") .forEach(System.out::print); System.out.println(); //Parallel stream created using Stream Stream.of("I", "work", "for", "ION").parallel() .map(s -> s + " ") .forEach(System.out::print); }
@Override public Collection<? extends Object> convert(Collection<?> value) { if (value == null || value.isEmpty()) { return Collections.emptyList(); } /** * Sort all elements by class first, then by our custom comparator. * If the collection is heterogeneous or has anonymous classes its useful * to first sort by the class name then by the comparator. We don't care * about that actual sort order, just that it is deterministic. */ Comparator<Object> comparator = Comparator.comparing(x -> x.getClass().getName()) .thenComparing(customComparators::compare); Collection<? extends Object> filtered = Seq.seq(value) .filter(Objects::nonNull) .sorted(comparator) .toList(); if (filtered.isEmpty()) { return Collections.emptyList(); } return filtered; }
@Test(expected=JsonMappingException.class) public void testCustomComparatorFails() throws JsonProcessingException { Set<MyObject> objects = Seq.of( new MyObject(2), new MyObject(4), new MyObject(3), new MyObject(1) ).toSet(Sets::newHashSet); mapper.writer().writeValueAsString(objects); }
private static Post postFromMeta(PostRaw postRaw) { PostMeta meta = metaFromPost(postRaw); Map<String, FileContent> fileContents = Seq.seq(postRaw.getGitFileReferences()) .map(GitHubSource.githubClient()::getFile) .toMap(fc -> fc.getName()); String content = Templating.instance().renderTemplate("templates/src/posts/" + postRaw.getSlug(), fileContents); return Post.builder() .postMeta(meta) .content(content) .build(); }
public static List<HtmlCssTheme> popularThemes() { HttpUrl url = HttpUrl.parse(POPULAR_THEMES_URL); Request request = new Request.Builder().url(url).get().build(); String html = Retry.retryUntilSuccessfulWithBackoff( () -> client.newCall(request).execute() ); Elements elements = Jsoup.parse(html).select(".item"); List<HtmlCssTheme> themes = Seq.seq(elements).map(BootstrapBayScraper::themeFromElement).toList(); return themes; }
public static List<HtmlCssTheme> popularThemes() { HttpUrl url = HttpUrl.parse(POPULAR_THEMES_URL); Request request = new Request.Builder().url(url).get().build(); String html = Retry.retryUntilSuccessfulWithBackoff( () -> client.newCall(request).execute() ); Elements elements = Jsoup.parse(html).select("#products .thumbnail"); List<HtmlCssTheme> themes = Seq.seq(elements).map(TemplateMonsterScraper::themeFromElement).toList(); return themes; }
private static List<String> genLibraries() throws MalformedURLException { WebSitemapGenerator wsg = new WebSitemapGenerator(HOST); List<JavaLib> libraries = Seq.of(JavaLib.values()).toList(); for (JavaLib lib : libraries) { String url = HttpUrl.parse(HOST) .newBuilder() .addPathSegment("java-libraries") .addPathSegment(lib.getName()) .build() .toString(); wsg.addUrl(url); } return wsg.writeAsStrings(); }
@Override public Map evaluateUnsafe(EvaluationContext context) { // evaluate all values for each key and return the resulting map return Seq.seq(map) .map(entry -> entry.map2(value -> value.evaluateUnsafe(context))) .toMap(Tuple2::v1, Tuple2::v2); }
@SafeVarargs public static AttributeDelegate create( AttributeDelegate root, Function<AttributeDelegate, AttributeDelegate>... childFns) { return Seq.foldLeft( Stream.of(childFns), root, (parent, childFn) -> childFn.apply(parent) ); }
/** * Computes the cumulated distance between the nodes in {@code nodes}. * * @see OSMUtils#distance(Node node1, Node node2) * @param nodes * list of nodes * @return sum of the distances between (n0,n1),(n1,n2),...,(nm-1,nm) */ public static OptionalDouble distance(List<Node> nodes) { return Seq.seq(nodes).sliding(2).map(n -> { List<Node> nodeList = n.collect(Collectors.toList()); if (nodeList.size() == 2) { return OSMUtils.distance(nodeList.get(0), nodeList.get(1)); } else { return null; } }).sum().filter(Objects::nonNull).map(OptionalDouble::of) .orElse(OptionalDouble.empty()); }
/** * Identifies all subways including those between pillar nodes and returns * the way segments of all of them. * * @param wayId * if of the OSM way * @param baseNodeId * id of the base node * @param adjNodeId * id of the adjacent node * @param edgeState * @return the ids of all way segments of the way {@code wayId} between the * base node {@code baseNodeId} and the adjacent node * {@code adjNodeId} */ List<WaySegmentId> getEdgeSegments(long wayId, long baseNodeId, long adjNodeId, EdgeIteratorState edgeState) { OSMData osmData = hopper.getOsmData(); // if the edge is virtual there are no data available because there is // now corresponding OSM way so we just return an empty list if (isVirtualEdge(edgeState.getEdge())) { logger.debug("virtual edge " + edgeState.getEdge() + ", distance = " + edgeState.getDistance()); return new ArrayList<>(); } PointList wayPoints = edgeState.fetchWayGeometry(3); List<Node> wayNodes = osmData.getWayNodes(wayId); List<Long> wayNodeIds = wayNodes.stream().map(Node::getId) .collect(Collectors.toList()); Long optAdjId = wayNodeIds.contains(adjNodeId) ? adjNodeId : null; // find the way nodes between the base node and the adjacent node List<Node> edgeNodes = wayNodeSearcher.getWayNodes(wayId, wayPoints, baseNodeId, optAdjId, edgeState); if (edgeNodes.size() != wayPoints.size()) { logger.debug("different number of wayNodes found: edgeNodes" + edgeNodes + "\nwayPoints = " + wayPoints); return new ArrayList<>(); } return Seq.seq(edgeNodes).sliding(2).map(s -> { List<Node> l = s.collect(Collectors.toList()); return new WaySegmentId(wayId, Pair.of(l.get(0).getId(), l.get(1).getId())); }).collect(Collectors.toList()); }
public String toCsvRecord() { String points = Seq.seq(this.path) .map(p -> p.getLat() + Evaluator.DELIMITER_POINT + p.getLon()) .collect(Collectors.joining(Evaluator.DELIMITER_POINT_LIST)); Object[] vals = new Object[] { id, iteration, timePoint, method, from.getId(), to.getId(), from.getLatitude(), from.getLongitude(), to.getLatitude(), to.getLongitude(), dist, costTemperature, costHeatIndex, duration, points }; return Arrays.stream(vals).map(String::valueOf) .collect(Collectors.joining(Evaluator.DELIMITER)); }
@Override public String toString() { StringBuilder row = new StringBuilder(); row.append(id); row.append(Evaluator.DELIMITER); row.append(this.iteration); row.append(Evaluator.DELIMITER); row.append(this.timePoint); row.append(Evaluator.DELIMITER); row.append(this.method); row.append(Evaluator.DELIMITER); row.append(this.from.getId()); row.append(Evaluator.DELIMITER); row.append(this.to.getId()); row.append(Evaluator.DELIMITER); row.append(this.from.getLatitude()); row.append(Evaluator.DELIMITER); row.append(this.from.getLongitude()); row.append(Evaluator.DELIMITER); row.append(this.to.getLatitude()); row.append(Evaluator.DELIMITER); row.append(this.to.getLongitude()); row.append(Evaluator.DELIMITER); row.append(this.dist); row.append(Evaluator.DELIMITER); row.append(this.costTemperature); row.append(Evaluator.DELIMITER); row.append(this.costHeatIndex); row.append(Evaluator.DELIMITER); row.append(this.duration); String points = Seq.seq(this.path) .map(p -> p.getLat() + Evaluator.DELIMITER_POINT + p.getLon()) .collect(Collectors.joining(Evaluator.DELIMITER_POINT_LIST)); row.append(Evaluator.DELIMITER); row.append(points); return row.toString(); }
static public List<SalonDocInfo> getSalonDocInfo(int salonID, SalonDB salonDB) throws SQLException { String sql = "SELECT * from salondocs join documents on doc_id = document_id where salon_id=?"; try (PreparedStatement stmt = salonDB.prep(sql)) { stmt.setLong(1, salonID); Seq<SalonDocInfo> docs = SQL.seq(stmt, Unchecked.function(rs -> { SalonDocInfo salondoc = new SalonDocInfo(); salondoc.docID = rs.getLong("document_id"); salondoc.type = rs.getString("document_type"); salondoc.authorID = rs.getInt("document_author_id"); salondoc.authorName = rs.getString("document_author"); salondoc.title = rs.getString("document_title"); salondoc.description = rs.getString("document_description"); salondoc.body = rs.getString("document_body"); salondoc.uploadDate = rs.getTimestamp("document_upload_date"); salondoc.viewDate = rs.getTimestamp("document_view_date"); salondoc.url = rs.getString("document_url"); salondoc.label1 = rs.getString("document_label1"); salondoc.label2 = rs.getString("document_label2"); salondoc.cat = rs.getString("document_cat"); salondoc.status = rs.getString("document_status"); salondoc.slider = rs.getString("document_slider"); salondoc.folder = rs.getLong("document_folder"); salondoc.mode = rs.getString("document_mode"); return salondoc; } )); return docs.toList(); } }
/** * Re-index all items in an index with the given type into another index, possible on another cluster. This method works with documents that * contain their unique id, the field which must be specified as the idField parameter. * * @param sourceIndex - The index from which to fetch documents. * @param type - The type of document to re-index. * @param targetIndex - The index (possibly on another cluster, based on the source and target clients) to re-index into. * @param documentsPerShard - The number of items to re-index per batch, per cluster shard. * @param idField - the document field containing the unique id of the document. */ public void reindex(String sourceIndex, String type, String targetIndex, int documentsPerShard, String idField) { SearchRequest searchRequest = new SearchRequest(new MatchAllQuery(), null, null); ScrollContext<Map> context = sourceClient.beginScanAndScroll(sourceIndex, type, searchRequest, documentsPerShard, "2m", Map.class); while (context.hasMore()) { ScrollResult<Map> data = sourceClient.continueScroll(context); List<Map> items = data.getData(); Map<String, Object> indexedData = Seq.seq(items) .toMap(item -> (String) item.get(idField), item -> item); targetClient.save(targetIndex, type, indexedData); context = data.getScrollContext(); } }
public List<String> getIndexNames() { return Seq.seq(indexSupplier.get().keySet()) .sorted() .toList(); }
public static Map<String, Object> asMap(Config config) { return Seq.seq(config.entrySet()) .toMap(e -> e.getKey(), e -> e.getValue().unwrapped()); }
public static List<PostMeta> getRecentPostsExcluding(Set<Long> excludeIds) { return Seq.seq(recentPosts) .filter(p -> !excludeIds.contains(p.getPostId())) .limit(10).toList(); }
public static List<PostMeta> getRecentPosts() { return Seq.seq(recentPosts).limit(10).toList(); }
public static List<PostMeta> getRecentPosts(int num) { return Seq.seq(recentPosts).limit(num).toList(); }