protected List<String> serviceNamesNotFoundInZipkin(List<io.zipkin.Span> spans) {
   List<String> serviceNamesFoundInAnnotations =
       spans
           .stream()
           .filter(span -> span.annotations != null)
           .map(span -> span.annotations)
           .flatMap(Collection::stream)
           .filter(span -> span.endpoint != null)
           .map(annotation -> annotation.endpoint)
           .map(endpoint -> endpoint.serviceName)
           .distinct()
           .collect(Collectors.toList());
   List<String> serviceNamesFoundInBinaryAnnotations =
       spans
           .stream()
           .filter(span -> span.binaryAnnotations != null)
           .map(span -> span.binaryAnnotations)
           .flatMap(Collection::stream)
           .filter(span -> span.endpoint != null)
           .map(annotation -> annotation.endpoint)
           .map(endpoint -> endpoint.serviceName)
           .distinct()
           .collect(Collectors.toList());
   List<String> names = new ArrayList<>();
   names.addAll(serviceNamesFoundInAnnotations);
   names.addAll(serviceNamesFoundInBinaryAnnotations);
   return names.contains(getAppName()) ? Collections.emptyList() : names;
 }
Beispiel #2
1
  public static void main(String... args) {

    List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
    numbers.stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);

    numbers.stream().limit(20).forEach(System.out::println);
  }
Beispiel #3
1
  public static void main(String[] args) {
    List<Person> persons = new LinkedList<>();
    persons.add(new Person("Bob", 19));
    persons.add(new Person("Bob", 65));
    persons.add(new Person("Arne", 32));
    persons.add(new Person("Arne", 10));
    persons.add(new Person("Arne", 40));
    persons.add(new Person("Kari", 27));
    persons.add(new Person("Gunvor", 90));
    persons.add(new Person("Kjell", 90));
    persons.add(new Person("Bob", 5));
    persons.add(new Person("Bob", 15));

    long nameCount = persons.stream().map(Person::getName).distinct().count();

    System.out.println("There are " + nameCount + " different names");

    int totalAge = persons.stream().mapToInt(Person::getAge).sum();

    System.out.println("The total age is " + totalAge);

    System.out.println("The following persons are of age:");
    persons
        .stream()
        .filter(p -> p.getAge() >= 18)
        .forEach(
            p -> {
              System.out.println("- " + p.getName());
            });
  }
 private void initializeExplicitConstructor(
     TurinTypeContructorDefinitionNode constructor, SymbolResolver resolver) {
   List<? extends FormalParameter> allParams = constructor.getParameters();
   List<FormalParameter> paramsWithoutDefaultValues =
       allParams
           .stream()
           .filter((p) -> !p.hasDefaultValue())
           .collect(Collectors.<FormalParameter>toList());
   List<String> paramSignatures =
       paramsWithoutDefaultValues
           .stream()
           .map((p) -> p.getType().jvmType().getSignature())
           .collect(Collectors.toList());
   boolean hasDefaultParameters =
       allParams.stream().filter((p) -> p.hasDefaultValue()).findFirst().isPresent();
   if (hasDefaultParameters) {
     paramSignatures.add("Ljava/util/Map;");
   }
   JvmConstructorDefinition constructorDefinition =
       new JvmConstructorDefinition(
           jvmType().getInternalName(), "(" + String.join("", paramSignatures) + ")V");
   constructors.add(
       new InternalConstructorDefinition(
           new ReferenceTypeUsage(this), allParams, constructorDefinition));
 }
  @Test
  public void _03_flatMap() {
    Stream<Stream<Character>> result = words.stream().map(w -> characterStream(w));

    // characterStream는 Stream<Stream<Character>>을 돌려주는데,
    // 이걸 한번 더 풀어서 Stream<Character>로 반환.
    Stream<Character> letters = words.stream().flatMap(w -> characterStream(w));
  }
  @SuppressWarnings("unchecked")
  public ResidentConverter(List<ObjectConverter.ColumnInfo> allColumns) throws java.io.IOException {
    Optional<ObjectConverter.ColumnInfo> column;

    final java.util.List<ObjectConverter.ColumnInfo> columns =
        allColumns
            .stream()
            .filter(
                it ->
                    "mixinReference".equals(it.typeSchema) && "Resident_entity".equals(it.typeName))
            .collect(Collectors.toList());
    columnCount = columns.size();

    readers = new ObjectConverter.Reader[columnCount];
    for (int i = 0; i < readers.length; i++) {
      readers[i] = (instance, rdr, ctx) -> StringConverter.skip(rdr, ctx);
    }

    final java.util.List<ObjectConverter.ColumnInfo> columnsExtended =
        allColumns
            .stream()
            .filter(
                it ->
                    "mixinReference".equals(it.typeSchema)
                        && "-ngs_Resident_type-".equals(it.typeName))
            .collect(Collectors.toList());
    columnCountExtended = columnsExtended.size();

    readersExtended = new ObjectConverter.Reader[columnCountExtended];
    for (int i = 0; i < readersExtended.length; i++) {
      readersExtended[i] = (instance, rdr, ctx) -> StringConverter.skip(rdr, ctx);
    }

    column = columns.stream().filter(it -> "id".equals(it.columnName)).findAny();
    if (!column.isPresent())
      throw new java.io.IOException(
          "Unable to find 'id' column in mixinReference Resident_entity. Check if DB is in sync");
    __index___id = (int) column.get().order - 1;

    column = columnsExtended.stream().filter(it -> "id".equals(it.columnName)).findAny();
    if (!column.isPresent())
      throw new java.io.IOException(
          "Unable to find 'id' column in mixinReference Resident. Check if DB is in sync");
    __index__extended_id = (int) column.get().order - 1;

    column = columns.stream().filter(it -> "birth".equals(it.columnName)).findAny();
    if (!column.isPresent())
      throw new java.io.IOException(
          "Unable to find 'birth' column in mixinReference Resident_entity. Check if DB is in sync");
    __index___birth = (int) column.get().order - 1;

    column = columnsExtended.stream().filter(it -> "birth".equals(it.columnName)).findAny();
    if (!column.isPresent())
      throw new java.io.IOException(
          "Unable to find 'birth' column in mixinReference Resident. Check if DB is in sync");
    __index__extended_birth = (int) column.get().order - 1;
  }
  public static void main(String... args) {

    System.out.println("Filtering with predicate");
    System.out.println("converte a stream to a List with Stream.collect(toList())");
    // Filtering with predicate
    List<Dish> vegetarianMenu = menu.stream().filter(Dish::isVegetarian).collect(toList());

    vegetarianMenu.forEach(System.out::println);

    System.out.println("Fitring even element and distinct");
    // Filtering unique elements
    List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
    numbers.stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);

    System.out.println("Limiting a Stream to X elements limit(x)");
    // Truncating a stream
    List<Dish> dishesLimit3 =
        menu.stream().filter(d -> d.getCalories() > 300).limit(3).collect(toList());

    dishesLimit3.forEach(System.out::println);

    System.out.println("Skiping X first elements in a stream skip(X)");
    // Skipping elements
    List<Dish> dishesSkip2 =
        menu.stream().filter(d -> d.getCalories() > 300).skip(2).collect(toList());

    dishesSkip2.forEach(System.out::println);
  }
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String inputData = scanner.nextLine();
    List<Team> championsLeague = new ArrayList<>();
    while (!inputData.equals("stop")) {
      String[] inputArgs = inputData.split("\\|+");
      String firstTeamName = inputArgs[0].trim();
      String secondTeamName = inputArgs[1].trim();

      if (!championsLeague.stream().anyMatch(t -> t.name.equals(firstTeamName))) {
        championsLeague.add(new Team(firstTeamName));
      }
      if (!championsLeague.stream().anyMatch(t -> t.name.equals(secondTeamName))) {
        championsLeague.add(new Team(secondTeamName));
      }

      Integer[] firstMatchResult =
          Arrays.stream(inputArgs[2].trim().split(":+"))
              .map(Integer::parseInt)
              .toArray(Integer[]::new);
      Integer[] secondMatchResult =
          Arrays.stream(inputArgs[3].trim().split(":+"))
              .map(Integer::parseInt)
              .toArray(Integer[]::new);

      Integer firstTeamGoals = firstMatchResult[0] + secondMatchResult[1];
      Integer secondTeamGoals = firstMatchResult[1] + secondMatchResult[0];

      Team firstTeam =
          championsLeague.stream().filter(t -> t.name.equals(firstTeamName)).findFirst().get();
      Team secondTeam =
          championsLeague.stream().filter(t -> t.name.equals(secondTeamName)).findFirst().get();

      if (firstTeamGoals > secondTeamGoals) {
        firstTeam.wins++;
      } else if (secondTeamGoals > firstTeamGoals) {
        secondTeam.wins++;
      } else if (firstTeamGoals.equals(secondTeamGoals)) {
        int firstTeamAwayGoals = secondMatchResult[1];
        int secondTeamAwayGoals = firstMatchResult[1];
        if (firstTeamAwayGoals > secondTeamAwayGoals) {
          firstTeam.wins++;
        } else {
          secondTeam.wins++;
        }
      }
      firstTeam.opponents.add(secondTeam);
      secondTeam.opponents.add(firstTeam);
      inputData = scanner.nextLine();
    }

    Collections.sort(championsLeague);
    championsLeague.forEach(System.out::println);
  }
  @Test
  public void _09_결과모으기() {
    // collect로 모으기
    HashSet<String> result = words.stream().collect(HashSet::new, HashSet::add, HashSet::addAll);

    // 통계 뽑기(합계, 평균, 최댓값, 최솟값등..)
    IntSummaryStatistics summary =
        words.stream().collect(Collectors.summarizingInt(String::length));
    assertThat(summary.getCount(), is(9989L));
    assertThat(summary.getAverage(), is(3.9401341475623184D));
    assertThat(summary.getMax(), is(14));
  }
Beispiel #10
0
  @Override
  public void create(int numberOfSuits, int numberOfRanks) {
    this.numberOfRanks = numberOfRanks;
    this.numberOfSuits = numberOfSuits;
    logger.info(
        format("*** Creating Deck with %s suits and %s ranks ***", numberOfSuits, numberOfRanks));

    List<Card.Suit> suits = Arrays.asList(Card.Suit.values()).subList(0, numberOfSuits);
    List<Card.Rank> ranks = Arrays.asList(Card.Rank.values()).subList(0, numberOfRanks);
    cards =
        suits
            .stream()
            .flatMap(suit -> ranks.stream().map(rank -> new Card(rank, suit)))
            .collect(toList());
  }
 private Option find(List<Option> options, String name) {
   final List<Option> match =
       options
           .stream()
           .filter(c -> c.getLongName().equalsIgnoreCase(name))
           .collect(Collectors.toList());
   if (match.isEmpty()) {
     fail(
         "Cannot find option '"
             + name
             + "' in "
             + options.stream().map(Option::getLongName).collect(Collectors.toList()));
   }
   return match.get(0);
 }
  @Override
  public void validate(
      final String key,
      final long totalOccurrences,
      final double percentContaining,
      final String... types) {
    final Optional<VarietyEntry> first =
        entries.stream().filter(entry -> entry.getKey().equals(key)).findFirst();
    if (!first.isPresent()) {
      Assert.fail("Entry with key '" + key + "' not found in variety results");
    }

    final VarietyEntry varietyEntry = first.get();
    Assert.assertEquals(
        "Failed to verify types of key " + key,
        new HashSet<>(Arrays.asList(types)),
        varietyEntry.getTypes());
    Assert.assertEquals(
        "Failed to verify total occurrences of key " + key,
        totalOccurrences,
        varietyEntry.getTotalOccurrences());
    Assert.assertEquals(
        "Failed to verify percents of key " + key,
        percentContaining,
        varietyEntry.getPercentContaining(),
        1e-15); // TODO: precision?
  }
Beispiel #13
0
  public Map<LocalDate, BigDecimal> getPlannedIncomePerDay(
      LocalDate dateFrom, LocalDate dateTo, ObservableList<Category> categories) {
    Map<LocalDate, BigDecimal> income = new TreeMap<>(Collections.reverseOrder());
    List<PlannedTransaction> transactions = getPlannedTransactions(dateFrom, dateTo, categories);
    for (LocalDate iterDate = dateTo;
        iterDate.isAfter(dateFrom.minusDays(1));
        iterDate = iterDate.minusDays(1)) {
      List<PlannedTransaction> transactionList = new LinkedList<>();
      for (PlannedTransaction transaction : transactions) {
        if (transaction.getDate().isAfter(iterDate.minusDays(1))
            && transaction.getDate().isBefore(iterDate.plusDays(1))) {
          transactionList.add(transaction);
        }
      }
      BigDecimal value =
          transactionList
              .stream()
              .filter(a -> a.getValue().compareTo(BigDecimal.ZERO) == 1)
              .map(a -> a.getValue().abs())
              .reduce(BigDecimal.ZERO, BigDecimal::add);

      if (value.compareTo(BigDecimal.ZERO) > 0) income.put(iterDate, value);
    }

    return income;
  }
  public void addChunkLoader(ChunkLoader chunkLoader) {
    Block block =
        getServer()
            .getWorld(chunkLoader.getWorld())
            .getBlockAt(chunkLoader.getX(), chunkLoader.getY(), chunkLoader.getZ());

    ChunkLoader existing =
        chunkLoaders.stream().filter(c -> c.getBlock().equals(block)).findFirst().orElse(null);

    if (existing != null) existing.delete();

    chunkLoader.setBlock(block);

    block.setType(getChunkLoaderMaterial(chunkLoader.getChunkType()));

    getChunkLoaders().add(chunkLoader);

    chunkLoader.load();

    data.saveChunkLoader(chunkLoader);

    Player player = getServer().getPlayer(chunkLoader.getOwner());
    if (player != null && player.isOnline())
      player.sendMessage(
          String.format(
              "%sSuccessfully placed %s chunk loader with and ID of %s and %s chunks",
              ChatColor.GOLD,
              chunkLoader.getChunkType(),
              chunkLoader.getId(),
              chunkLoader.getSize()));
  }
 private void find(MessageContext context, String args) {
   DiscordApiClient apiClient = context.getApiClient();
   Channel channel = context.getChannel();
   Pattern pattern;
   try {
     pattern = Pattern.compile(args);
   } catch (PatternSyntaxException pse) {
     apiClient.sendMessage(loc.localize("commands.admin.find.response.invalid"), channel);
     return;
   }
   Predicate<String> matcher = pattern.asPredicate();
   List<User> results =
       context
           .getServer()
           .getMembers()
           .stream()
           .map(Member::getUser)
           .filter(u -> matcher.test(u.getUsername()))
           .collect(Collectors.toList());
   int size = results.size();
   if (size > 20) {
     apiClient.sendMessage(loc.localize("commands.admin.find.response.oversize", size), channel);
     return;
   }
   StringJoiner resultJoiner = new StringJoiner(", ");
   results.stream().map(this::userToResult).forEach(resultJoiner::add);
   apiClient.sendMessage(
       loc.localize("commands.admin.find.response.format", size, resultJoiner.toString()),
       channel);
 }
 public static Stream<Character> characterStream(String s) {
   List<Character> result = new ArrayList<>();
   for (char c : s.toCharArray()) {
     result.add(c);
   }
   return result.stream();
 }
Beispiel #17
0
 public static List<String> toBase64(List<Classifier> classifiers) {
   return classifiers
       .stream()
       .map(MLServiceImpl::toBase64)
       .filter(Objects::nonNull)
       .collect(Collectors.toList());
 }
 public List<TurinTypeContructorDefinitionNode> getExplicitConstructors() {
   return members
       .stream()
       .filter((m) -> m instanceof TurinTypeContructorDefinitionNode)
       .map((m) -> (TurinTypeContructorDefinitionNode) m)
       .collect(Collectors.toList());
 }
Beispiel #19
0
 public static List<Classifier> fromBase64(List<String> base64EncodedClassifiers) {
   return base64EncodedClassifiers
       .stream()
       .map(MLServiceImpl::fromBase64)
       .filter(Objects::nonNull)
       .collect(Collectors.toList());
 }
  @Override
  public APIBlockIdList getBlockIds(BID blockId, int count) throws BCSAPIException {
    try (ConnectorSession session = connection.createSession()) {
      log.trace("get " + count + " block ids from " + blockId);

      ConnectorProducer blockIdsRequestProducer =
          session.createProducer(session.createQueue("blockIdsRequest"));

      ConnectorMessage m = session.createMessage();
      BCSAPIMessage.BLKIDSREQ.Builder builder = BCSAPIMessage.BLKIDSREQ.newBuilder();
      if (blockId != null) {
        builder.setBlockHash(ByteString.copyFrom(blockId.unsafeGetArray()));
      }
      if (count <= 0) count = 20;
      builder.setCount(count);
      m.setPayload(builder.build().toByteArray());
      byte[] response = synchronousRequest(session, blockIdsRequestProducer, m);
      if (response != null) {
        BCSAPIMessage.BLKIDS message = BCSAPIMessage.BLKIDS.parseFrom(response);
        List<ByteString> blockIdsList = message.getBlockIdsList();
        List<BID> blockIds =
            blockIdsList.stream().map(bs -> new BID(bs.toByteArray())).collect(Collectors.toList());
        return new APIBlockIdList(
            blockIds,
            message.getHeight(),
            message.hasPreviousBlockId()
                ? new BID(message.getPreviousBlockId().toByteArray())
                : null);
      }
    } catch (ConnectorException | InvalidProtocolBufferException e) {
      throw new BCSAPIException(e);
    }

    return null;
  }
 private List<Prediction> filterToSelectedPredictionDistances(
     DateTime start, List<Prediction> predictions) {
   return predictions
       .stream()
       .filter(p -> predictionsDistancesToStore.contains(new Duration(start, p.timestamp)))
       .collect(toList());
 }
 @Override
 public Optional<Catalog> findBySeriesId(int id) {
   return catalogs
       .stream()
       .filter(c -> c.getId() == id && c.getType() == CatalogType.SERIES)
       .findFirst();
 }
  public void upgradeToCurrentVersion() {
    if (isInitialImport()) {
      initialImports.forEach(InitialImport::performInitialImport);
      versionProvider.writeLastVersion(getCurrentVersion());
    } else if (getLastVersion().get() < getCurrentVersion()) {
      List<VersionUpgrade> upgraders = new ArrayList<>(upgrades);
      Collections.sort(upgraders);

      upgraders
          .stream()
          .filter(upgrader -> upgrader.getVersion() > getLastVersion().get())
          .forEach(
              upgrader -> {
                log.info(
                    "Performing upgrade from version {} to {} using {}",
                    getLastVersion(),
                    upgrader.getVersion(),
                    upgrader.getClass().getSimpleName());
                upgrader.performUpgrade();
              });
      versionProvider.writeLastVersion(getCurrentVersion());
    } else {
      log.debug("no upgrade nessessary");
    }
  }
 public static List<CtMethod> filterTest(List<CtMethod> newTests, JunitResult result) {
   final List<String> goodTests = result.goodTests();
   return newTests
       .stream()
       .filter(test -> goodTests.contains(test.getSimpleName()))
       .collect(Collectors.toList());
 }
Beispiel #25
0
  public Map<LocalDate, BigDecimal> getIncomePerDay(
      LocalDate dateFrom, LocalDate dateTo, List<Account> accounts, List<Category> categories) {
    Map<LocalDate, BigDecimal> income = new TreeMap<>(Collections.reverseOrder());
    List<ExternalTransaction> transactions =
        getTransactions(dateFrom, dateTo, accounts, categories);
    for (LocalDate iterDate = dateTo;
        iterDate.isAfter(dateFrom.minusDays(1));
        iterDate = iterDate.minusDays(1)) {
      List<ExternalTransaction> transactionList = new LinkedList<>();
      for (ExternalTransaction transaction : transactions) {
        if ((compareDates(transaction.dateProperty().get(), iterDate.minusDays(1)) == 1)
            && (compareDates(transaction.dateProperty().get(), iterDate.plusDays(1)) == -1)) {
          transactionList.add(transaction);
        }
      }
      BigDecimal value =
          transactionList
              .stream()
              .filter(a -> a.deltaProperty().get().compareTo(BigDecimal.ZERO) == 1)
              .map(a -> a.deltaProperty().get().abs())
              .reduce(BigDecimal.ZERO, BigDecimal::add);

      if (value.compareTo(BigDecimal.ZERO) > 0) income.put(iterDate, value);
    }

    return income;
  }
  private void processWithoutGrouping(List<TaskWithWorklogs> tasks, DisplayData displayData) {
    LOGGER.debug("Processing without grouping");
    tasks
        .stream()
        .sorted((o1, o2) -> COLLATOR.compare(o1.getIssue(), o2.getIssue()))
        .forEach(
            taskWithWorklogs -> {
              DisplayRow row = new DisplayRow();
              row.setIssueId(taskWithWorklogs.getIssue());
              row.setLabel(taskWithWorklogs.getSummary());
              row.setResolvedDate(taskWithWorklogs.getResolved());

              taskWithWorklogs
                  .getWorklogItemList()
                  .forEach(
                      worklogItem -> {
                        LocalDate date = worklogItem.getDate();
                        DisplayDayEntry workdayEntry =
                            row.getWorkdayEntry(date)
                                .orElseGet(
                                    () -> {
                                      DisplayDayEntry newWorkdayEntry = new DisplayDayEntry();
                                      newWorkdayEntry.setDate(date);
                                      row.addDisplayDayEntry(newWorkdayEntry);
                                      return newWorkdayEntry;
                                    });

                        workdayEntry.getSpentTime().addAndGet(worklogItem.getDurationInMinutes());
                      });

              displayData.addRow(new TreeItem<>(row));
            });
  }
Beispiel #27
0
 public List<Note> getNotesForVoice(int voice) {
   return notes
       .stream()
       .filter(n -> n.getVoice() == voice)
       .sorted(comparing(Note::getPosition))
       .collect(toList());
 }
Beispiel #28
0
  private static List<Double> getWeightVectorForClass(
      Map<String, List<LinkedHashMap<String, Object>>> documents,
      String key,
      List<Integer> featureIndexList,
      GraphDatabaseService db) {
    List<Double> weightVector;

    Transaction tx = db.beginTx();
    // Get class id
    Long classId =
        db.findNodesByLabelAndProperty(DynamicLabel.label("Class"), "name", key)
            .iterator()
            .next()
            .getId();

    // Get weight vector for class
    List<Long> longs =
        documents
            .get(key)
            .stream()
            .map(a -> ((Integer) a.get("feature")).longValue())
            .collect(Collectors.toList());

    weightVector =
        featureIndexList
            .stream()
            .map(i -> longs.contains(i.longValue()) ? tfidf(db, i.longValue(), classId) : 0.0)
            .collect(Collectors.toList());
    tx.success();
    tx.close();
    return weightVector;
  }
 @Override
 public Optional<Catalog> findMovieById(int id) {
   return catalogs
       .stream()
       .filter(c -> c.getId() == id && c.getType() == CatalogType.MOVIE)
       .findFirst();
 }
 private List<Expr> prefixedConstants(List<String> tokens) {
   return tokens
       .stream()
       .filter(t -> t != null)
       .map(t -> prefixedConstant(t))
       .collect(Collectors.toList());
 }