public static void main(String[] args) { // stream.collect(collector): values // Collectors.groupingBy(classifier) Stream<Locale> locales = Stream.of(Locale.getAvailableLocales()); Map<String, List<Locale>> languageToLocales = locales.collect(Collectors.groupingBy(Locale::getDisplayLanguage)); System.out.println(languageToLocales); System.out.println("--------------"); // stream.collect(collector): values // Collectors.groupingBy(classifier, downstream) locales = Stream.of(Locale.getAvailableLocales()); Map<String, Long> languageToLocalesCounting = locales.collect(Collectors.groupingBy(Locale::getDisplayLanguage, Collectors.counting())); System.out.println(languageToLocalesCounting); System.out.println("--------------"); // stream.collect(collector): values // Collectors.partitioningBy(predicate) locales = Stream.of(Locale.getAvailableLocales()); Map<Boolean, List<Locale>> englishAndOtherLocales = locales.collect(Collectors.partitioningBy(l -> l.getLanguage().equals("en"))); List<Locale> englishLocales = englishAndOtherLocales.get(true); System.out.println(englishLocales); System.out.println("--------------"); }
public static void main(String[] args) { List<Participante> participantes = ParticipantesTdc.listaTodos(); // Operações Simples participantes.stream().count(); boolean participantInscrito = participantes.stream().anyMatch(Participante::isInscrito); Optional<String> optionalEmail2 = participantes.stream().map(Participante::getEmail).findAny(); // Collectors List<String> emailsList = participantes.stream().map(Participante::getEmail).collect(Collectors.toList()); List<String> emailsLinkedList = participantes .stream() .map(Participante::getEmail) .collect(Collectors.toCollection(LinkedList::new)); Set<String> emailsSet = participantes.stream().map(Participante::getEmail).collect(Collectors.toSet()); Map<TamanhoCamisa, List<Participante>> participantesPorTamanho = participantes.stream().collect(Collectors.groupingBy(Participante::getTamanhoCamisa)); Map<TamanhoCamisa, List<String>> emailsPorTamanho = participantes .stream() .collect( Collectors.groupingBy( Participante::getTamanhoCamisa, Collectors.mapping(Participante::getEmail, Collectors.toList()))); }
public Map<Championship, Map<Season, List<HockeyMatch>>> groupAllMatchesByChampionshipAndSeasons() { List<HockeyMatch> all = findAll(); Map<Championship, Map<Season, List<HockeyMatch>>> collect = all.stream() .collect( Collectors.groupingBy( HockeyMatch::getChampionship, Collectors.groupingBy(HockeyMatch::getSeason))); return collect; }
public static void main(String[] args) { final List<Person> people = Arrays.asList( new Person("Robert", 49), new Person("John", 20), new Person("Sara", 21), new Person("Chloe", 18), new Person("Jane", 21), new Person("Greg", 35)); List<Person> olderThan20_a = new ArrayList<>(); people.stream().filter(person -> person.age > 20).forEach(person -> olderThan20_a.add(person)); printPeople("don't trust olderThan20_a", olderThan20_a); List<Person> olderThan20_b = people .stream() .filter(person -> person.age > 20) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); printPeople("don't trust olderThan20_b", olderThan20_b); List<Person> olderThan20_c = people.stream().filter(person -> person.age > 20).collect(Collectors.toList()); printPeople("don't trust olderThan20_c", olderThan20_c); Map<Integer, List<Person>> peopleByAge = people.stream().collect(Collectors.groupingBy(person -> person.age)); System.out.println("Grouped by age: " + peopleByAge); Map<Integer, List<String>> nameOfPeopleByAge = people .stream() .collect( Collectors.groupingBy( person -> person.age, Collectors.mapping(person -> person.name, Collectors.toList()))); System.out.println("People grouped by age: " + nameOfPeopleByAge); // Group the names by their first char and then get the oldest person in // each group Comparator<Person> byAge = Comparator.comparing(person -> person.age); Map<Character, Optional<Person>> oldestPersonOfEachLetter = people .stream() .collect( Collectors.groupingBy( person -> person.name.charAt(0), Collectors.reducing(BinaryOperator.maxBy(byAge)))); System.out.println("Oldest person of each letter:"); System.out.println(oldestPersonOfEachLetter); }
private Availability firstAssignation(AID alumn) { if (this.groups.containsKey(alumn)) { System.err.println("WARN: Requested first assignation for already registered alumn " + alumn); return this.groups.get(alumn); } // TODO: This could be more optimized, for example, having the // availabilityCount map cached // Get the count of the current availabilities final Map<Availability, Long> availabilityCount = this.groups.values().stream().collect(Collectors.groupingBy(a -> a, Collectors.counting())); // Get the current available groups final List<Availability> availableGroups = TeacherBehaviour.AVAILABLE_GROUPS .stream() .filter( a -> availabilityCount.getOrDefault(a, 0l) < TeacherBehaviour.MAX_ALUMNS_PER_GROUP) .collect(Collectors.toList()); // Pick a random one final Availability result = availableGroups.get(this.random.nextInt(availableGroups.size())); this.groups.put(alumn, result); return result; }
@Test public void vote() throws Exception { ObjectMapper mapper = new ObjectMapper(); Restaurant restaurantB = mapper.readValue(new StringReader(testRestaurantJson1), Restaurant.class); restaurantRepository.saveAndFlush(restaurantB); Restaurant restaurantA = mapper.readValue(new StringReader(testRestaurantJson2), Restaurant.class); restaurantRepository.saveAndFlush(restaurantA); doVote(restaurantB.getRestaurantName(), "qqq"); doVote(restaurantB.getRestaurantName(), "www"); doVote(restaurantB.getRestaurantName(), "ddd"); doVote(restaurantA.getRestaurantName(), "kkk"); doVote(restaurantA.getRestaurantName(), "lll"); List<Vote> votes = votesRepository.findAll(); // check all votes are here assertEquals(MAX_TOTAL_VOTES, votes.size()); Map<Long, Long> res = votes.stream().collect(Collectors.groupingBy(Vote::getRestaurantId, Collectors.counting())); // check all votes counter correctly assertEquals(3l, res.get(restaurantB.getId()).longValue()); assertEquals(2l, res.get(restaurantA.getId()).longValue()); }
public static void main(String[] args) { Map<Integer, HashSet<String>> withSet = Stream.of("jon", "andrew", "harvey", "bil") .collect(Collectors.groupingBy(String::length, HashSet::new)); out.println(withSet); }
@Test public void testMapping() { List<String> input = Arrays.asList("Capital", "lower", "Foo", "bar"); Collector<String, ?, Map<Boolean, Optional<Integer>>> collector = MoreCollectors.partitioningBy( str -> Character.isUpperCase(str.charAt(0)), MoreCollectors.mapping(String::length, MoreCollectors.first())); checkShortCircuitCollector( "mapping", new BooleanMap<>(Optional.of(7), Optional.of(5)), 2, input::stream, collector); Collector<String, ?, Map<Boolean, Optional<Integer>>> collectorLast = MoreCollectors.partitioningBy( str -> Character.isUpperCase(str.charAt(0)), MoreCollectors.mapping(String::length, MoreCollectors.last())); checkCollector( "last", new BooleanMap<>(Optional.of(3), Optional.of(3)), input::stream, collectorLast); input = Arrays.asList("Abc", "Bac", "Aac", "Abv", "Bbc", "Bgd", "Atc", "Bpv"); Map<Character, List<String>> expected = EntryStream.of('A', Arrays.asList("Abc", "Aac"), 'B', Arrays.asList("Bac", "Bbc")).toMap(); AtomicInteger cnt = new AtomicInteger(); Collector<String, ?, Map<Character, List<String>>> groupMap = Collectors.groupingBy( s -> s.charAt(0), MoreCollectors.mapping( x -> { cnt.incrementAndGet(); return x; }, MoreCollectors.head(2))); checkCollector("groupMap", expected, input::stream, groupMap); cnt.set(0); assertEquals(expected, input.stream().collect(groupMap)); assertEquals(4, cnt.get()); }
/** * Process supported manifest headers (Startup-Component and Provide-Capability). * * <p>Process Startup-Component headers and create StartupComponent instances. * * <p>Process Provide-Capability headers to calculate the expected number of required * capabilities. * * <p>Process Provide-Capability headers to get a list of CapabilityProviders and * RequiredCapabilityListeners. * * @param bundleList list of bundles to be scanned for Provide-Capability headers. * @param supportedManifestHeaders list of manifest headers processed by this method. */ private void processManifestHeaders( List<Bundle> bundleList, List<String> supportedManifestHeaders) { Map<String, List<ManifestElement>> groupedManifestElements = bundleList .stream() // Filter out all the supported manifest headers. .filter( bundle -> AccessController.doPrivileged( (PrivilegedAction<Boolean>) () -> isSupportedManifestHeaderExists(bundle, supportedManifestHeaders))) // Process filtered manifest headers and get a list of ManifestElements. .flatMap(bundle -> extractManifestElements(bundle, supportedManifestHeaders).stream()) // Partition all the ManifestElements with the manifest header name. .collect(Collectors.groupingBy(ManifestElement::getValue)); if (groupedManifestElements.get(STARTUP_LISTENER_COMPONENT) != null) { processStartupComponents(groupedManifestElements.get(STARTUP_LISTENER_COMPONENT)); } if (groupedManifestElements.get(OSGI_SERVICE_COMPONENT) != null) { processOSGiServiceCapabilities(groupedManifestElements.get(OSGI_SERVICE_COMPONENT)); } // You can add logic to handle other types of provide capabilities here. // e.g. custom manifest headers, config files etc. }
private List<LDObject> mergeLocations(List<LDObject> ldObjects) { Map<String, List<LDObject>> r = ldObjects .stream() .parallel() .collect( Collectors.groupingBy( ldObject -> { return ldObject.getMap().get("locationId").getValues().get(0); })); List<LDObject> finalLocationForJourney = new ArrayList<>(); final LDObject[] finalObj = {null}; r.forEach( (k, v) -> { v.stream() .forEach( ldObject -> { if (finalObj[0] == null) { finalObj[0] = ldObject; } else { finalObj[0].merge(ldObject); } }); finalLocationForJourney.add(finalObj[0]); finalObj[0] = null; }); return finalLocationForJourney; }
public static void main(String[] args) { final Collection<Task> tasks = Arrays.asList( new Task(Status.OPEN, 5), new Task(Status.OPEN, 13), new Task(Status.CLOSED, 8)); // 在这个task集合中一共有多少个OPEN状态的点?在Java 8之前,要解决这个问题,则需要使用foreach循环遍历task集合;但是在Java // 8中可以利用steams解决:包括一系列元素的列表,并且支持顺序和并行处理。 final long totalPointsOfOpenTasks = tasks .stream() .filter(task -> task.getStatus() == Status.OPEN) .mapToInt(Task::getPoints) .sum(); System.out.println("Total points: " + totalPointsOfOpenTasks); /** * Steam之上的操作可分为中间操作和晚期操作。 * * <p>中间操作会返回一个新的steam——执行一个中间操作(例如filter)并不会执行实际的过滤操作,而是创建一个新的steam, * 并将原steam中符合条件的元素放入新创建的steam。 * * <p>晚期操作(例如forEach或者sum),会遍历steam并得出结果或者附带结果;在执行晚期操作之后,steam处理线已经处理完毕, * 就不能使用了。在几乎所有情况下,晚期操作都是立刻对steam进行遍历。 */ // steam的另一个价值是创造性地支持并行处理(parallel processing)。对于上述的tasks集合,我们可以用下面的代码计算所有任务的点数之和: // Calculate total points of all tasks final double totalPoints = tasks .stream() .parallel() .map(task -> task.getPoints()) // or map( Task::getPoints ) .reduce(0, Integer::sum); System.out.println("Total points (all tasks): " + totalPoints); // 对于一个集合,经常需要根据某些条件对其中的元素分组。利用steam提供的API可以很快完成这类任务,代码如下: // Group tasks by their status final Map<Status, List<Task>> map = tasks.stream().collect(Collectors.groupingBy(Task::getStatus)); System.out.println(map); // 最后一个关于tasks集合的例子问题是:如何计算集合中每个任务的点数在集合中所占的比重,具体处理的代码如下: // Calculate the weight of each tasks (as percent of total points) final Collection<String> result = tasks .stream() // Stream< String > .mapToInt(Task::getPoints) // IntStream .asLongStream() // LongStream .mapToDouble(points -> points / totalPoints) // DoubleStream .boxed() // Stream< Double > .mapToLong(weigth -> (long) (weigth * 100)) // LongStream .mapToObj(percentage -> percentage + "%") // Stream< String> .collect(Collectors.toList()); // List< String > System.out.println(result); // [19%, 50%, 30%] }
@Test public void _11_그룹핑() { final Stream<Locale> stream = Stream.of(Locale.getAvailableLocales()); Map<String, List<Locale>> countryToLocales = stream.collect( Collectors.groupingBy(Locale::getCountry) // 묶을 기준값 ); System.out.println(countryToLocales.get("CH")); }
@Test public void gruppiereNachNachnamen() { Map<String, List<Person>> gruppiertNachNachnamen = newPersonenStream() // .collect(Collectors.groupingBy(Person::getNachname)); assertThat(gruppiertNachNachnamen.keySet(), hasSize(100)); assertThat(gruppiertNachNachnamen.get("Müller"), hasSize(1000)); assertThat(gruppiertNachNachnamen.get("Schuster"), hasSize(1000)); }
private void checkResults(Restaurant restA, Restaurant restB) { List<Vote> votes = votesRepository.findAll(); // check changing vote doesn't create new entries assertEquals(MAX_TOTAL_VOTES, votes.size()); Map<Long, Long> res = votes.stream().collect(Collectors.groupingBy(Vote::getRestaurantId, Collectors.counting())); // check that vote actually changed assertEquals(2l, res.get(restB.getId()).longValue()); assertEquals(3l, res.get(restA.getId()).longValue()); }
/** * Run time: O(n) can use bit vector also * * @param input * @return */ static boolean hasUnique(String input) { if (input == null || input.isEmpty()) return true; Map<Character, Long> map = input .chars() .mapToObj(c -> (char) c) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); return !map.entrySet().stream().anyMatch(x -> x.getValue() > 1); }
void buildInMem() { Collection<EntityType> data = dataSrcFun.apply(dataSrc); java.util.Map<String, Set<String>> setMap = data.stream() .collect( Collectors.groupingBy( e -> keyToStringFun.apply(keyGetFun.apply(e)), Collectors.mapping( e -> memberToStringFun.apply(memberGetFun.apply(e)), Collectors.toSet()))); setMapAdapter.putInMem(mapName, setMap); }
public static void main(String[] args) { final List<Person> people = Arrays.asList( new Person("John", 20), new Person("Sara", 21), new Person("Jane", 21), new Person("Greg", 35)); List<Person> olderThan20 = people .stream() .filter(person -> person.getAge() > 20) .collect(ArrayList::new, ArrayList::add, ArrayList::addAll); System.out.println("People older than 20: " + olderThan20); List<Person> olderThan20_1 = people.stream().filter(person -> person.getAge() > 20).collect(Collectors.toList()); System.out.println("People older than 20: " + olderThan20_1); Map<Integer, List<Person>> peopleByAge = people.stream().collect(Collectors.groupingBy(Person::getAge)); System.out.println("Grouped by age: " + peopleByAge); Map<Integer, List<String>> nameOfPeopleByAge = people .stream() .collect( Collectors.groupingBy( Person::getAge, Collectors.mapping(Person::getName, Collectors.toList()))); System.out.println("People name grouped by age: " + nameOfPeopleByAge); Comparator<Person> byAge = Comparator.comparing(Person::getAge); Map<Character, Optional<Person>> oldestPersonOfEachCharacter = people .stream() .collect( Collectors.groupingBy( person -> person.getName().charAt(0), Collectors.reducing(BinaryOperator.maxBy(byAge)))); System.out.println("Oldest person of each letter: " + oldestPersonOfEachCharacter); }
public static void main(String[] args) { Map<Long, Long> collect = IntStream.range(0, 10) .mapToObj(Long::valueOf) .collect(Collectors.groupingBy(i -> i, reducing((a, b) -> a))); System.out.println(collect); Map<Long, Long> collect2 = IntStream.range(0, 10).mapToObj(Long::valueOf).collect(Collectors.toMap(i -> i, i -> i)); System.out.println(collect2); }
public Graph(String line) { map = Arrays.stream( (line.trim() + " " + new StringBuilder(line.trim()).reverse().toString()) .split(" ")) .collect( Collectors.groupingBy( x -> ((String) x).charAt(0), Collectors.mapping( x -> ((String) x).charAt(1), Collectors.toCollection(LinkedHashSet<Character>::new)))); }
public void restore(boolean writeMode, Long manifestIdDefault) { List<CmsCIRelation> watchedBys; long counter = 0; long restoredMonitors = 0; if (manifestIdDefault == null) { watchedBys = cmProcessor.getCIRelationsNsLikeNakedNoAttrs("/", "manifest.WatchedBy", null, null, null); } else { watchedBys = cmManager.getFromCIRelations(manifestIdDefault, "manifest.WatchedBy", null); } long startTime = System.currentTimeMillis(); Map<Long, List<CmsCIRelation>> monitors = watchedBys.stream().collect(Collectors.groupingBy(CmsCIRelation::getFromCiId)); for (Long manifestId : monitors.keySet()) { counter++; List<CmsCIRelation> realizedAsRels = cmManager.getFromCIRelations(manifestId, "base.RealizedAs", null); if (realizedAsRels.isEmpty()) continue; Set<Long> cmsBomCiIds = realizedAsRels.stream().map(CmsCIRelation::getToCiId).collect(Collectors.toSet()); restoreRealizedAsMapping(manifestId, cmsBomCiIds, writeMode); boolean isFirstBom = true; for (CmsCIRelation relation : realizedAsRels) { restoreManifestMapping(manifestId, relation.getToCiId(), writeMode); if (isFirstBom) { for (CmsCIRelation rel : monitors.get(manifestId)) { if (rel.getToCi() == null) { rel.setToCi(cmProcessor.getCiById(rel.getToCiId())); } if (restoreMonitor(manifestId, relation.getToCiId(), rel.getToCi(), writeMode)) { restoredMonitors++; } } } isFirstBom = false; } if (counter % 100 == 0) { logger.info( "Time to process " + counter + " - " + (System.currentTimeMillis() - startTime) + " ms!"); } } logger.info(">>>>>>>>>>> Monitor restored " + restoredMonitors + ";"); logger.info( ">>>>>>>>>>> Monitor restoration is done!!!" + counter + " - " + (System.currentTimeMillis() - startTime) + " ms!"); }
/** * Build TrendContent with external services top by average response time. * * @param period * @param limit * @param timeRange * @param transactions * @param transactionsStatistic * @return */ public static TrendContext<String> topByAvgResponseTime( Long period, Integer limit, TimeRange timeRange, Iterable<ExternalService> transactions, Iterable<ExternalServiceStatistic> transactionsStatistic) { TrendContext<String> trendContext = new TrendContext<>(period * 1000, timeRange); Map<Long, ExternalService> externalServiceMap = StreamSupport.stream(transactions.spliterator(), false) .collect(Collectors.toMap(ExternalService::getId, (t) -> t)); Map<String, List<ExternalServiceStatistic>> transactionStatisticMap = StreamSupport.stream(transactionsStatistic.spliterator(), false) .collect( Collectors.groupingBy( statistic -> { Long serviceId = statistic.getExternalServiceId(); ExternalService transaction = externalServiceMap.get(serviceId); return transaction.getUrl(); })); transactionStatisticMap .entrySet() .stream() .sorted( Comparator.comparing( new Function<Map.Entry<String, List<ExternalServiceStatistic>>, Double>() { @Override public Double apply(Map.Entry<String, List<ExternalServiceStatistic>> entry) { DoubleSummaryStatistics responseSummaryStatistics = entry .getValue() .stream() .filter(statistic -> statistic.getSumResponseTime() != null) .mapToDouble(ExternalServiceStatistic::getSumResponseTime) .summaryStatistics(); LongSummaryStatistics pvSummaryStatistics = entry .getValue() .stream() .filter(statistic -> statistic.getPv() != null) .mapToLong(ExternalServiceStatistic::getPv) .summaryStatistics(); return calculateRate( responseSummaryStatistics.getSum(), pvSummaryStatistics.getSum()); } })) .limit(limit) .forEach(entry -> trendContext.addStatistics(entry.getKey(), timeRange, entry.getValue())); return trendContext; }
@Benchmark public void parallel_lazy_jdk() { Map<Alphagram, List<String>> groupBy = this.guavaWords.parallelStream().collect(Collectors.groupingBy(Alphagram::new)); groupBy .entrySet() .parallelStream() .map(Map.Entry::getValue) .filter(list -> list.size() >= SIZE_THRESHOLD) .sorted(Comparator.<List<String>>comparingInt(List::size).reversed()) .map(list -> list.size() + ": " + list) .forEach(e -> Assert.assertFalse(e.isEmpty())); }
@RequestMapping("/gameStatus") public ResponseEntity<GameStatus> broadcastGameStatus() { GameStatus gameStatus = new GameStatus(); Iterable<GameStep> gameSteps = gameStepRepository.findAll(); List<GameStep> collect = StreamSupport.stream(gameSteps.spliterator(), false).collect(toList()); Map<String, List<GameStep>> gameStepByUser = StreamSupport.stream(gameSteps.spliterator(), false) .collect(Collectors.groupingBy(GameStep::getUserPseudo)); for (Map.Entry<String, List<GameStep>> gameStepByUserEntry : gameStepByUser.entrySet()) { UserGameStatus userGameStatus = new UserGameStatus(); userGameStatus.setPseudo(gameStepByUserEntry.getKey()); Map<Step, List<GameStep>> gameStepByStep = gameStepByUserEntry.getValue().stream().collect(Collectors.groupingBy(GameStep::getStep)); for (Map.Entry<Step, List<GameStep>> gameStepByStepEntry : gameStepByStep.entrySet()) { gameStepByStepEntry .getValue() .stream() .min(Comparator.comparing(GameStep::getInstant)) .ifPresent( gameStep -> { userGameStatus .getStepInfos() .add(new StepInfo(gameStep.getStep(), gameStep.getInstant())); }); } gameStatus.getUserGameStatus().add(userGameStatus); } webSocketTemplate.convertAndSend("/topic/gameStatus", gameStatus); return new ResponseEntity<GameStatus>(gameStatus, HttpStatus.OK); }
@Test public void testCollectors() { ArrayList<Person> people = new ArrayList<>(); ArrayList<Integer> things = new ArrayList<>(); ArrayList<Employee> employees = new ArrayList<>(); ArrayList<Student> students = new ArrayList<>(); // Accumulate names into a List List<String> list = people.stream().map(Person::getName).collect(Collectors.toList()); // Accumulate names into a TreeSet Set<String> list2 = people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new)); // Convert elements to strings and concatenate them, separated by commas String joined = things.stream().map(Object::toString).collect(Collectors.joining(", ")); // Find highest-paid employee Optional<Employee> highestPaid = employees.stream().collect(Collectors.maxBy(Comparator.comparingInt(Employee::getSalary))); // Group employees by department Map<Department, List<Employee>> byDept = employees.stream().collect(Collectors.groupingBy(Employee::getDepartment)); // Find highest-paid employee by department Map<Department, Optional<Employee>> highestPaidByDept = employees .stream() .collect( Collectors.groupingBy( Employee::getDepartment, Collectors.maxBy(Comparator.comparingInt(Employee::getSalary)))); // Partition students into passing and failing Map<Boolean, List<Student>> passingFailing = students.stream().collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD)); }
/** * Returns a partitioned collection of lane number to Tile objects from the provided basecall * directory. */ public static Map<Integer, ? extends Collection<Tile>> readLaneTiles( final File illuminaRunDirectory, final ReadStructure readStructure) { final Collection<Tile> tiles; try { tiles = TileMetricsUtil.parseTileMetrics( TileMetricsUtil.renderTileMetricsFileFromBasecallingDirectory(illuminaRunDirectory), readStructure); } catch (final FileNotFoundException e) { throw new PicardException("Unable to open laneMetrics file.", e); } return tiles.stream().collect(Collectors.groupingBy(Tile::getLaneNumber)); }
// Good reading: https://en.wikipedia.org/wiki/Permutation private static double numOfPerms(int[] seq) { // Note that the sequence may potentially have repeating elements Map<Integer, Long> freq = Arrays.stream(seq) .boxed() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); // https://en.wikipedia.org/wiki/Permutation#Permutations_of_multisets double numOfPerms = factorial(seq.length); for (long uniqElemFreq : freq.values()) { // according to the problem description, max size of permutation is in [2..18] range numOfPerms /= factorial((int) uniqElemFreq); } return numOfPerms; }
@Benchmark public void serial_lazy_streams_ec() { Map<Alphagram, Set<String>> groupBy = this.ecWords .stream() .collect(Collectors.groupingBy(Alphagram::new, Collectors.<String>toSet())); groupBy .entrySet() .stream() .map(Map.Entry::getValue) .filter(list -> list.size() >= SIZE_THRESHOLD) .sorted(Comparator.<Set<String>>comparingInt(Set::size).reversed()) .map(list -> list.size() + ": " + list) .forEach(e -> Assert.assertFalse(e.isEmpty())); }
@RequestMapping("/events/{eventName}/additional-field") public List<TicketFieldConfigurationAndAllDescriptions> getAllAdditionalField( @PathVariable("eventName") String eventName) { final Map<Integer, List<TicketFieldDescription>> descById = ticketFieldRepository .findDescriptions(eventName) .stream() .collect(Collectors.groupingBy(TicketFieldDescription::getTicketFieldConfigurationId)); return ticketFieldRepository .findAdditionalFieldsForEvent(eventName) .stream() .map( field -> new TicketFieldConfigurationAndAllDescriptions( field, descById.getOrDefault(field.getId(), Collections.emptyList()))) .collect(Collectors.toList()); }
@Cacheable(value = "KLineBuss.queryAllGroup") public List<KLineGroup> queryAllGroup() { Map<Date, Map<String, KLine>> kLineMap = kLineRepos .findAll() .stream() .collect( Collectors.groupingBy( KLine::getDt, Collectors.toMap(KLine::getCode, kLine -> kLine))); List<KLineGroup> list = kLineMap .entrySet() .stream() .map(entry -> new KLineGroup(entry.getKey(), entry.getValue())) .sorted() .collect(Collectors.toList()); return Collections.unmodifiableList(list); }
static Map<String, MatchedDataPair> matchData( DataSource xSource, MergeType xMergeType, DataSource ySource, MergeType yMergeType, Resolution resolution) { List<String> commonKeys = xSource .getData() .keySet() .stream() .filter((key) -> ySource.getData().containsKey(key)) .map(resolution::toKey) .distinct() .collect(Collectors.toList()); Function<DataSource, Map<String, List<Double>>> dataOrganizer = (source) -> source .getData() .entrySet() .stream() .filter((entry) -> commonKeys.contains(resolution.toKey(entry))) .collect( Collectors.groupingBy( (entry) -> resolution.toKey(entry), Collectors.mapping((entry) -> entry.getValue(), Collectors.toList()))); Map<String, List<Double>> xData = dataOrganizer.apply(xSource); Map<String, List<Double>> yData = dataOrganizer.apply(ySource); Map<String, MatchedDataPair> matches = commonKeys .stream() .collect( Collectors.<String, String, MatchedDataPair>toMap( key -> key, key -> new MatchedDataPair( xMergeType.merge(xData.get(key)), yMergeType.merge(yData.get(key))))); return matches; }