org.junit.runners.Parameterized.Parameters#java.util.stream.Collectors源码实例Demo

下面列出了org.junit.runners.Parameterized.Parameters#java.util.stream.Collectors 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@Override
public List<T> doShrink(SourceOfRandomness random, T larger) {
  @SuppressWarnings("unchecked")
  List<Object> asList = new ArrayList<>(larger);

  List<T> shrinks = new ArrayList<>();
  shrinks.addAll(removals(asList));

  @SuppressWarnings("unchecked")
  Shrink<Object> generator = (Shrink<Object>) componentGenerators().get(0);

  List<List<Object>> oneItemShrinks = shrinksOfOneItem(random, asList, generator);
  shrinks.addAll(oneItemShrinks.stream().map(this::convert).filter(this::inSizeRange)
      .collect(Collectors.toList()));

  return shrinks;
}
 
源代码2 项目: openhab-core   文件: EnrichedThingDTOMapperTest.java
@Test
public void shouldMapEnrichedThingDTO() {
    when(linkedItemsMap.get("1")).thenReturn(Stream.of("linkedItem1", "linkedItem2").collect(Collectors.toSet()));

    EnrichedThingDTO enrichedThingDTO = EnrichedThingDTOMapper.map(thing, thingStatusInfo, firmwareStatus,
            linkedItemsMap, true);

    assertThat(enrichedThingDTO.editable, is(true));
    assertThat(enrichedThingDTO.firmwareStatus, is(equalTo(firmwareStatus)));
    assertThat(enrichedThingDTO.statusInfo, is(equalTo(thingStatusInfo)));
    assertThat(enrichedThingDTO.thingTypeUID, is(equalTo(thing.getThingTypeUID().getAsString())));
    assertThat(enrichedThingDTO.label, is(equalTo(THING_LABEL)));
    assertThat(enrichedThingDTO.bridgeUID, is(CoreMatchers.nullValue()));

    assertChannels(enrichedThingDTO);

    assertThat(enrichedThingDTO.configuration.values(), is(empty()));
    assertThat(enrichedThingDTO.properties, is(equalTo(properties)));
    assertThat(enrichedThingDTO.location, is(equalTo(LOCATION)));
}
 
private <T> Map<String, T> convertMap(Map map) {
  if (map.isEmpty()) { 
    return (Map<String, T>) map; 
  } 
   
  Object elem = map.values().stream().findFirst().get(); 
  if (!(elem instanceof Map) && !(elem instanceof List)) { 
    return (Map<String, T>) map; 
  } else { 
    Function<Object, T> converter; 
    if (elem instanceof List) { 
      converter = object -> (T) new JsonArray((List) object); 
    } else { 
      converter = object -> (T) new JsonObject((Map) object); 
    } 
    return ((Map<String, T>) map).entrySet() 
     .stream() 
     .collect(Collectors.toMap(Map.Entry::getKey, converter::apply)); 
  } 
}
 
源代码4 项目: baleen   文件: ProperNounInformationCollector.java
@Override
public <T extends Entity> Set<EntityInformation<T>> getEntityInformation(
    JCas jCas, Class<T> clazz) {
  Multimap<ReferenceTarget, T> map = ReferentUtils.createReferentMap(jCas, clazz);
  Map<T, List<Sentence>> index = JCasUtil.indexCovering(jCas, clazz, Sentence.class);
  Map<T, List<WordToken>> tokens = JCasUtil.indexCovered(jCas, clazz, WordToken.class);

  Set<EntityInformation<T>> infos = new HashSet<>();
  for (Map.Entry<ReferenceTarget, Collection<T>> entry : map.asMap().entrySet()) {
    Collection<Sentence> sentences =
        entry.getValue().stream().flatMap(m -> index.get(m).stream()).collect(Collectors.toSet());

    List<T> properNouns =
        entry.getValue().stream()
            .filter(
                e ->
                    tokens.get(e).stream()
                        .map(WordToken::getPartOfSpeech)
                        .anyMatch("NNP"::equals))
            .collect(toList());

    infos.add(new EntityInformation<T>(entry.getKey(), properNouns, sentences));
  }

  return infos;
}
 
源代码5 项目: gatk   文件: MTLowHeteroplasmyFilterToolTest.java
@Test(dataProvider = "lowhetData")
public void testLowHetVariantsFiltered(List<List<String>> expectedASFilters) {
    final Set<Integer> low_het_sites = new HashSet<>(Arrays.asList(301));
    final File outputFile = createTempFile("low-het-test", ".vcf");
    final ArgumentsBuilder argsBuilder = new ArgumentsBuilder()
            .addReference(MITO_REF.getAbsolutePath())
            .add(StandardArgumentDefinitions.VARIANT_SHORT_NAME, NA12878_MITO_FILTERED_VCF.getAbsolutePath())
            .add(MTLowHeteroplasmyFilterTool.MAX_ALLOWED_LOW_HETS_LONG_NAME, 0)
            .addOutput(outputFile);
    runCommandLine(argsBuilder);
    Set<VariantContext> variants = VariantContextTestUtils.streamVcf(outputFile)
            .filter(vcf -> vcf.getFilters().contains(GATKVCFConstants.LOW_HET_FILTER_NAME)).collect(Collectors.toSet());
    Set<Integer> actual_sites = variants.stream().map(var -> var.getStart()).collect(Collectors.toSet());
    Assert.assertEquals(actual_sites, low_het_sites, "did not find the correct " + GATKVCFConstants.LOW_HET_FILTER_NAME + " site filters.");

    final List<List<String>> actualASFilters = VariantContextTestUtils.streamVcf(outputFile)
            .map(vc -> AnnotationUtils.decodeAnyASListWithRawDelim(vc.getCommonInfo().getAttributeAsString(GATKVCFConstants.AS_FILTER_STATUS_KEY, ""))).collect(Collectors.toList());
    Assert.assertEquals(actualASFilters, expectedASFilters);

}
 
源代码6 项目: pravega   文件: ExtendedS3StorageTest.java
TestContext() throws Exception {
    String bucketName = BUCKET_NAME_PREFIX + UUID.randomUUID().toString();
    this.adapterConfig = ExtendedS3StorageConfig.builder()
            .with(ExtendedS3StorageConfig.CONFIGURI, configUri)
            .with(ExtendedS3StorageConfig.BUCKET, bucketName)
            .with(ExtendedS3StorageConfig.PREFIX, "samplePrefix")
            .build();
    s3Config = new ConfigUri<>(S3Config.class).parseUri(configUri);
    s3Proxy = new S3ProxyImpl(configUri, s3Config);
    s3Proxy.start();
    client = new S3JerseyClientWrapper(s3Config, s3Proxy);
    client.createBucket(bucketName);
    List<ObjectKey> keys = client.listObjects(bucketName).getObjects().stream()
            .map(object -> new ObjectKey(object.getKey()))
            .collect(Collectors.toList());

    if (!keys.isEmpty()) {
        client.deleteObjects(new DeleteObjectsRequest(bucketName).withKeys(keys));
    }
}
 
源代码7 项目: cloudbreak   文件: HueConfigProviderTest.java
@Test
public void getServiceConfigVariables() {
    BlueprintView blueprintView = getMockBlueprintView("7.2.0", "7.1.0");

    RDSConfig rdsConfig = new RDSConfig();
    rdsConfig.setType(HUE);
    rdsConfig.setConnectionURL(String.format("jdbc:%s://%s:%s/%s", DB_PROVIDER, HOST, PORT, DB_NAME));
    rdsConfig.setConnectionUserName(USER_NAME);
    rdsConfig.setConnectionPassword(PASSWORD);
    TemplatePreparationObject tpo = new Builder()
            .withRdsConfigs(Set.of(rdsConfig))
            .withBlueprintView(blueprintView)
            .build();

    List<ApiClusterTemplateVariable> result = underTest.getServiceConfigVariables(tpo);
    Map<String, String> paramToVariable =
            result.stream().collect(Collectors.toMap(ApiClusterTemplateVariable::getName, ApiClusterTemplateVariable::getValue));
    assertThat(paramToVariable).containsOnly(
            new SimpleEntry<>("hue-hue_database_host", HOST),
            new SimpleEntry<>("hue-hue_database_port", PORT),
            new SimpleEntry<>("hue-hue_database_name", DB_NAME),
            new SimpleEntry<>("hue-hue_database_type", DB_PROVIDER),
            new SimpleEntry<>("hue-hue_database_user", USER_NAME),
            new SimpleEntry<>("hue-hue_database_password", PASSWORD));
}
 
源代码8 项目: uyuni   文件: ActionChainManager.java
/**
 * Schedules the application of states to minions
 * @param user the requesting user
 * @param sids list of system IDs
 * @param test for test mode
 * @param earliest earliest execution date
 * @param actionChain Action Chain instance
 * @return a set of Actions
 * @throws TaskomaticApiException if there was a Taskomatic error
 * (typically: Taskomatic is down)
 */
public static Set<Action> scheduleApplyStates(User user, List<Long> sids, Optional<Boolean> test,
                                               Date earliest, ActionChain actionChain)
        throws TaskomaticApiException {

    if (!sids.stream().map(sid -> ServerFactory.lookupById(sid))
            .filter(server -> !MinionServerUtils.isMinionServer(server))
            .collect(Collectors.toList()).isEmpty()) {
        throw new IllegalArgumentException("Server ids include non minion servers.");
    }

    Set<Long> sidSet = new HashSet<Long>();
    sidSet.addAll(sids);

    String summary = "Apply highstate" + (test.isPresent() && test.get() ? " in test-mode" : "");
    Set<Action> result = scheduleActions(user, ActionFactory.TYPE_APPLY_STATES, summary,
            earliest, actionChain, null, sidSet);
    for (Action action : result) {
        ApplyStatesActionDetails applyState = new ApplyStatesActionDetails();
        applyState.setActionId(action.getId());
        test.ifPresent(t -> applyState.setTest(t));
        ((ApplyStatesAction)action).setDetails(applyState);
        ActionFactory.save(action);
    }
    return result;
}
 
源代码9 项目: analysis-model   文件: FileNameResolverTest.java
@Test
@DisplayName("Should set path if the relative file name exists")
void shouldSetPath() {
    Report report = new Report();

    IssueBuilder builder = new IssueBuilder();

    report.add(builder.setFileName(RELATIVE_FILE).build());

    resolvePaths(report, RESOURCE_FOLDER_PATH);

    assertThat(report).hasSize(1);
    assertThat(report.get(0)).hasFileName(RELATIVE_FILE).hasPath(RESOURCE_FOLDER_STRING);

    assertThat(report.getInfoMessages()).hasSize(1);
    assertThat(report.getInfoMessages().get(0)).as("Files: "
            + report.stream().map(Issue::getFileName).collect(Collectors.joining(", ")))
            .contains("1 found", "0 not found");
    assertThat(report.getErrorMessages()).isEmpty();
}
 
源代码10 项目: dhis2-core   文件: DataSetController.java
@RequestMapping( value = "/{uid}/categoryCombos", method = RequestMethod.GET )
public @ResponseBody RootNode getCategoryCombinations( @PathVariable( "uid" ) String uid, HttpServletRequest request,
    TranslateParams translateParams, HttpServletResponse response )
    throws Exception
{
    setUserContext( translateParams );
    DataSet dataSet = manager.get( DataSet.class, uid );

    if ( dataSet == null )
    {
        throw new WebMessageException( WebMessageUtils.conflict( "Data set does not exist: " + uid ) );
    }

    List<CategoryCombo> categoryCombos = dataSet.getDataSetElements().stream().
        map( DataSetElement::getResolvedCategoryCombo ).distinct().collect( Collectors.toList() );

    Collections.sort( categoryCombos );

    List<String> fields = Lists.newArrayList( contextService.getParameterValues( "fields" ) );

    RootNode rootNode = NodeUtils.createMetadata();
    rootNode.addChild( fieldFilterService.toCollectionNode( CategoryCombo.class,
        new FieldFilterParams( categoryCombos, fields ) ) );

    return rootNode;
}
 
源代码11 项目: DataflowTemplates   文件: KafkaUnboundedReader.java
@Override
public CheckpointMark getCheckpointMark() {
  reportBacklog();
  return new KafkaCheckpointMark(
      partitionStates
          .stream()
          .map(
              p ->
                  new PartitionMark(
                      p.topicPartition.topic(),
                      p.topicPartition.partition(),
                      p.nextOffset,
                      p.lastWatermark.getMillis()))
          .collect(Collectors.toList()),
      source.getSpec().isCommitOffsetsInFinalizeEnabled() ? Optional.of(this) : Optional.empty());
}
 
源代码12 项目: modeldb   文件: AutogenPathDatasetBlob.java
public ai.verta.modeldb.versioning.PathDatasetBlob.Builder toProto() {
  ai.verta.modeldb.versioning.PathDatasetBlob.Builder builder =
      ai.verta.modeldb.versioning.PathDatasetBlob.newBuilder();
  {
    if (this.Components != null && !this.Components.equals(null) && !this.Components.isEmpty()) {
      Function<ai.verta.modeldb.versioning.PathDatasetBlob.Builder, Void> f =
          x -> {
            builder.addAllComponents(
                this.Components.stream()
                    .map(y -> y.toProto().build())
                    .collect(Collectors.toList()));
            return null;
          };
      f.apply(builder);
    }
  }
  return builder;
}
 
源代码13 项目: o2oa   文件: TimerApplicationStubs.java
private ProcessStubs concreteProcessStubs(Business business, String applicationId) throws Exception {
	EntityManager em = business.entityManagerContainer().get(Process.class);
	CriteriaBuilder cb = em.getCriteriaBuilder();
	CriteriaQuery<Process> cq = cb.createQuery(Process.class);
	Root<Process> root = cq.from(Process.class);
	Predicate p = cb.equal(root.get(Process_.application), applicationId);
	cq.select(root).where(p);
	List<Process> os = em.createQuery(cq).getResultList();
	List<ProcessStub> list = new ArrayList<>();
	for (Process o : os) {
		ProcessStub stub = new ProcessStub();
		stub.setName(o.getName());
		stub.setValue(o.getId());
		stub.setActivityStubs(this.concreteActivityStubs(business, o.getId()));
		list.add(stub);
	}
	list = list.stream().sorted(Comparator.comparing(ProcessStub::getName, Comparator.nullsLast(String::compareTo)))
			.collect(Collectors.toList());
	ProcessStubs stubs = new ProcessStubs();
	stubs.addAll(list);
	return stubs;
}
 
源代码14 项目: Kepler   文件: GameBattleShip.java
/**
 * Count the ships placed on the map.
 *
 * @param shipType the ship type (optional)
 * @param player the player (optional)
 * @return the count of the ships
 */
private int countShips(GameShipType shipType, Player player) {
    List<GameShip> gameShipType = null;

    if (shipType != null) {
        if (player != null) {
            gameShipType = this.shipsPlaced.keySet().stream().filter(ship -> ship.getShipType() == shipType && ship.getPlayer() == player).collect(Collectors.toList());
        } else {
            gameShipType = this.shipsPlaced.keySet().stream().filter(ship -> ship.getShipType() == shipType).collect(Collectors.toList());
        }
    } else {
        if (player != null) {
            gameShipType = this.shipsPlaced.keySet().stream().filter(ship -> ship.getPlayer() == player).collect(Collectors.toList());
        } else {
            gameShipType = new ArrayList<>(this.shipsPlaced.keySet());
        }
    }

    return gameShipType.size();
}
 
源代码15 项目: ifsc-rest-api   文件: BankService.java
public ResponseEntity<GenericResponse<List<String>>> fuzzySearchBank(LikeBranchSearch likeBranchSearch) {
    GenericResponse<List<String>> response = new GenericResponse<>();
    if (mBankList != null && mBankList.length > 0) {
        List<ExtractedResult> levenshteinList = FuzzySearch.extractSorted(likeBranchSearch.getBankName(), Arrays.asList(mBankList), LEVENSHTEIN_CUTOFF);
        List<String> bankList = levenshteinList.stream().map(ExtractedResult::getString).collect(Collectors.toList());
        if (bankList.size() > 0) {
            response.setData(bankList);
            response.setStatus(STATUS_SUCCESS);
        } else {
            response.setStatus(STATUS_FAILED);
            response.setMessage("No bank found with name " + likeBranchSearch.getBankName());
        }

    } else {
        response.setStatus(STATUS_FAILED);
        response.setMessage("Something went wrong. Please try again");
    }
    return new ResponseEntity<>(response, HttpStatus.OK);
}
 
源代码16 项目: robot   文件: ExplainOperation.java
/**
 * Render axiom tree in indented Markdown using the provided renderer.
 *
 * @param tree indented collection of axioms
 * @param renderer renderer for displaying axioms and entities
 * @return
 */
private static String renderTree(Tree<OWLAxiom> tree, OWLObjectRenderer renderer) {
  StringBuilder builder = new StringBuilder();
  if (tree.isRoot()) {
    builder.append("## ");
    builder.append(renderer.render(tree.getUserObject()));
    builder.append(" ##");
    builder.append("\n");
  } else {
    String padding =
        tree.getPathToRoot().stream().skip(1).map(x -> "  ").collect(Collectors.joining());
    builder.append(padding);
    builder.append("- ");
    builder.append(renderer.render(tree.getUserObject()));
  }
  if (!tree.isLeaf()) builder.append("\n");
  String children =
      tree.getChildren()
          .stream()
          .map(child -> renderTree(child, renderer))
          .collect(Collectors.joining("\n"));
  builder.append(children);
  return builder.toString();
}
 
源代码17 项目: BungeeChat2   文件: BungeecordModuleManager.java
public static List<BungeeChatModule> getLocalModules() {
  if (localModules == null) {
    localModules =
        Arrays.stream(BungeecordModuleManager.class.getDeclaredFields())
            .filter(field -> BungeeChatModule.class.isAssignableFrom(field.getType()))
            .map(
                field -> {
                  try {
                    return (BungeeChatModule) field.get(null);
                  } catch (IllegalArgumentException | IllegalAccessException e) {
                    e.printStackTrace();

                    return null;
                  }
                })
            .collect(Collectors.toList());
  }

  return localModules;
}
 
源代码18 项目: tlaplus   文件: Model.java
private void pruneOldestSnapshots() throws CoreException {
	// Sort model by snapshot timestamp and remove oldest ones.
	final int snapshotKeepCount = TLCActivator.getDefault().getPreferenceStore().getInt(TLCActivator.I_TLC_SNAPSHOT_KEEP_COUNT);
	// Filter out running snapshots such as remotely running ones (CloudTLC).
	final List<Model> snapshotModels = new ArrayList<>(getSnapshots().stream()
			.filter(m -> !m.isRunning() && !m.isRunningRemotely()).collect(Collectors.toList()));
	if (snapshotModels.size() > snapshotKeepCount) {
	    final int pruneCount = snapshotModels.size() - snapshotKeepCount;
	    Collections.sort(snapshotModels, new Comparator<Model>() {
	        public int compare (final Model model1, final Model model2) {
	        	final long ts1 = model1.getSnapshotTimeStamp();
	        	final long ts2 = model2.getSnapshotTimeStamp();
	        	return Long.compare(ts1, ts2);
	        }
	    });
	    for (int i = 0; i < pruneCount; i++) {
	        final Model model = snapshotModels.get(i);
	        model.delete(new NullProgressMonitor());
	    }
	}
}
 
源代码19 项目: symbol-sdk-java   文件: BinarySerializationImpl.java
@Override
public TransactionFactory fromBodyBuilder(NetworkType networkType, Serializer transactionBuilder) {

    AccountAddressRestrictionTransactionBodyBuilder builder = (AccountAddressRestrictionTransactionBodyBuilder) transactionBuilder;

    long restrictionFlagsValue = builder.getRestrictionFlags().stream()
        .mapToLong(AccountRestrictionFlagsDto::getValue).sum();

    AccountAddressRestrictionFlags restrictionFlags = AccountAddressRestrictionFlags
        .rawValueOf((int) restrictionFlagsValue);

    List<UnresolvedAddress> restrictionAdditions = builder.getRestrictionAdditions().stream()
        .map(SerializationUtils::toUnresolvedAddress).collect(Collectors.toList());

    List<UnresolvedAddress> restrictionDeletions = builder.getRestrictionDeletions().stream()
        .map(SerializationUtils::toUnresolvedAddress).collect(Collectors.toList());

    return AccountAddressRestrictionTransactionFactory
        .create(networkType, restrictionFlags, restrictionAdditions, restrictionDeletions);
}
 
源代码20 项目: terracotta-platform   文件: ManagementRegistry.java
private static Map<String, Object> toMap(Capability capability) {
  Map<String, Object> map = new LinkedHashMap<>();
  map.put("name", capability.getName());
  map.put("context", capability.getCapabilityContext().getAttributes().stream().map(ManagementRegistry::toMap).collect(Collectors.toList()));

  List<Map<String, Object>> descriptorList = new ArrayList<>(capability.getDescriptors().size());
  map.put("descriptors", descriptorList);
  for (Descriptor o : capability.getDescriptors()) {
    if (o instanceof CallDescriptor) {
      descriptorList.add(toMap((CallDescriptor) o));
    } else if (o instanceof StatisticDescriptor) {
      descriptorList.add(toMap((StatisticDescriptor) o));
    } else if (o instanceof Settings) {
      descriptorList.add(toMap((Settings) o));
    } else {
      descriptorList.add(toMap(o));
    }
  }
  return map;
}
 
/**
 * Creates a ConnectionModel from a ConnectionInformation
 *
 * @param connection
 * 		the {@link ConnectionInformation} object
 * @param location
 * 		the {@link RepositoryLocation} of the connection
 * @param editable
 *        {@code true} if the connection is editable
 * @return a connection model containing the information of the connection
 */
public static ConnectionModel fromConnection(ConnectionInformation connection, RepositoryLocation location, boolean editable) {
	List<ValueProviderModel> valueProviderModels = connection.getConfiguration().getValueProviders().stream().map(ValueProviderModelConverter::toModel).collect(Collectors.toList());
	ConnectionModel conn = new ConnectionModel(connection, location, editable, valueProviderModels);
	conn.setDescription(connection.getConfiguration().getDescription());
	conn.setTags(new ArrayList<>(connection.getConfiguration().getTags()));
	// use new (empty) connection to capture all potential new parameters
	ConnectionInformation newConnection = null;
	try {
		ConnectionHandler handler = ConnectionHandlerRegistry.getInstance().getHandler(connection.getConfiguration().getType());
		newConnection = handler.createNewConnectionInformation("emptyCI");
	} catch (GenericHandlerRegistry.MissingHandlerException e) {
		LogService.getRoot().log(Level.WARNING, "com.rapidminer.connection.gui.model.ConnectionModelConverter.creating_empty_connection_failed", connection.getConfiguration().getType());
	}
	if (newConnection != null) {
		addParameters(newConnection, conn);
	}
	// now overwrite with values of existing connection
	addParameters(connection, conn);
	for (PlaceholderParameter p : connection.getConfiguration().getPlaceholders()) {
		conn.addOrSetPlaceholder(p.getGroup(), p.getName(), p.getValue(), p.isEncrypted(), p.getInjectorName(), p.isEnabled());
	}
	conn.setLibraryFiles(connection.getLibraryFiles());
	conn.setOtherFiles(connection.getOtherFiles());
	return conn;
}
 
源代码22 项目: selenium   文件: TestFileLocator.java
private static Set<Path> getExcludedFiles(final Path testDirectory) {
  String excludedFiles = getProperty(TEST_EXCLUDES_PROPERTY);
  if (excludedFiles == null) {
    return emptySet();
  }

  Iterable<String> splitExcludes = Splitter.on(',').omitEmptyStrings().split(excludedFiles);

  return StreamSupport.stream(splitExcludes.spliterator(), false)
      .map(testDirectory::resolve).collect(Collectors.toSet());
}
 
源代码23 项目: cubedb   文件: CubeUtils.java
public static Map<String, Map<String, Map<String, Long>>> searchResultsToMap(
    Map<GroupedSearchResultRow, Long> in) {
  return in.entrySet()
      .stream()
      .collect(
          Collectors.groupingBy(
              e -> e.getKey().getFieldName(),
              Collectors.groupingBy(
                  e -> e.getKey().getFieldValue(),
                  Collectors.groupingBy(
                      e -> e.getKey().getMetricName(),
                      Collectors.summingLong(e -> e.getValue().longValue())))));
}
 
源代码24 项目: epcis   文件: CachedTraversalEngine.java
/**
 * Add in step to the traversal engine
 *
 * Path Enabled -> Greedy,
 * 
 * Path Disabled -> Lazy
 *
 * Pipeline: Stream<CachedChronoVertex> -> Stream<CachedChronoVertex> (flatMap)
 *
 * Path: Map<CachedChronoVertex, Set<CachedChronoVertex>>
 *
 * @param branchFactor
 *            the number of max adjacent vertices for each incoming vertex
 * @param labels
 *            the edge labels to traverse
 * @return the extended Stream
 */
public CachedTraversalEngine in(final BsonArray labels, final int branchFactor) {
	// Check Input element class
	checkInputElementClass(CachedChronoVertex.class);

	// Stream Update
	if (isPathEnabled) {
		// Get Sub-Path
		Map intermediate = (Map) stream.distinct().map(v -> {
			CachedChronoVertex cv = (CachedChronoVertex) v;
			return new AbstractMap.SimpleImmutableEntry(cv,
					cv.getChronoVertexSet(Direction.IN, labels, branchFactor));
		}).collect(Collectors.toMap(e -> ((Entry) e).getKey(), e -> ((Entry) e).getValue()));

		// Update Path
		updateTransformationPath(intermediate);

		// Make stream again
		stream = getStream(intermediate, isParallel);
	} else {
		stream = stream.flatMap(v -> {
			return ((CachedChronoVertex) v).getChronoVertexStream(Direction.IN, labels, branchFactor, isParallel);
		});
	}
	// Step Update
	final Class[] args = new Class[2];
	args[0] = BsonArray.class;
	args[1] = Integer.TYPE;
	final Step step = new Step(this.getClass().getName(), "in", args, labels, branchFactor);
	stepList.add(step);

	// Set Class
	elementClass = CachedChronoVertex.class;
	return this;
}
 
源代码25 项目: hesperides   文件: PlatformHistory.java
public List<ApplicationOutput> buildApplicationOutputs() {
    Map<String, List<PlatformBuilder>> applicationPlatformsMap = platforms.stream()
            .filter(platform -> !platform.isDeleted)
            .map(PlatformTimestampedBuilders::getTimestampedBuilders)
            .map(PlatformHistory::getLastPlatformBuilder)
            .collect(Collectors.groupingBy(PlatformBuilder::getApplicationName));

    return applicationPlatformsMap.entrySet().stream()
            .map(entry -> buildApplicationOutput(entry.getKey(), entry.getValue(), false))
            .collect(Collectors.toList());
}
 
源代码26 项目: bisq   文件: MediationDisputeList.java
public static MediationDisputeList fromProto(protobuf.MediationDisputeList proto,
                                             CoreProtoResolver coreProtoResolver,
                                             Storage<MediationDisputeList> storage) {
    List<Dispute> list = proto.getDisputeList().stream()
            .map(disputeProto -> Dispute.fromProto(disputeProto, coreProtoResolver))
            .collect(Collectors.toList());
    list.forEach(e -> e.setStorage(storage));
    return new MediationDisputeList(storage, list);
}
 
源代码27 项目: oneops   文件: FqdnExecutor.java
private ProvisionedGslb provisionedGslb(CmsWorkOrderSimple wo, TorbitConfig torbitConfig, InfobloxConfig infobloxConfig, String logKey) {
  Context context = context(wo, infobloxConfig);
  List<String> aliases = getAliasesWithDefault(context, wo.getRfcCi().getCiAttributes()).stream()
      .collect(Collectors.toList());
  List<CloudARecord> cloudEntries = getCloudDnsEntry(context, wo.getCloud());
  return ProvisionedGslb.builder()
      .torbitConfig(torbitConfig)
      .infobloxConfig(infobloxConfig)
      .app(context.platform)
      .subdomain(context.subdomain)
      .cnames(aliases)
      .cloudARecords(cloudEntries)
      .logContextId(logKey)
      .build();
}
 
@Override
public List<BuildConfigurationAudited> findAllByIdOrderByRevDesc(Integer buildConfigurationId) {

    List<Object[]> result = AuditReaderFactory.get(entityManager)
            .createQuery()
            .forRevisionsOfEntity(BuildConfiguration.class, false, false)
            .add(AuditEntity.id().eq(buildConfigurationId))
            .addOrder(AuditEntity.revisionNumber().desc())
            .getResultList();

    return result.stream().map(o -> createAudited(o[0], o[1])).collect(Collectors.toList());
}
 
源代码29 项目: immutables   文件: ReactorReader.java
public ReactorMapperTuple.DistinctLimitOffset select(Iterable<Projection<?>> projections) {
  Objects.requireNonNull(projections, "projections");
  Preconditions.checkArgument(!Iterables.isEmpty(projections), "empty projections");
  List<Expression> expressions = StreamSupport.stream(projections.spliterator(), false).map(Matchers::toExpression).collect(Collectors.toList());
  Query newQuery = this.query.addProjections(expressions);
  return new ReactorMappers.MapperTuple(newQuery, session);
}
 
源代码30 项目: Java-Coding-Problems   文件: Strings.java
public static String removeCharacterV3(String str, char ch) {

        if (str == null || str.isEmpty()) {
            // or throw IllegalArgumentException
            return "";
        }

        return str.chars()
                .filter(c -> c != ch)
                .mapToObj(c -> String.valueOf((char) c))
                .collect(Collectors.joining());
    }