com.google.common.collect.Maps#uniqueIndex ( )源码实例Demo

下面列出了com.google.common.collect.Maps#uniqueIndex ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: buck   文件: Pom.java
private void updateModel(Artifact mavenCoordinates, Iterable<Artifact> deps) {
  model.setGroupId(mavenCoordinates.getGroupId());
  model.setArtifactId(mavenCoordinates.getArtifactId());
  model.setVersion(mavenCoordinates.getVersion());
  if (Strings.isNullOrEmpty(model.getName())) {
    model.setName(mavenCoordinates.getArtifactId()); // better than nothing
  }

  // Dependencies
  ImmutableMap<DepKey, Dependency> depIndex =
      Maps.uniqueIndex(getModel().getDependencies(), DepKey::new);
  for (Artifact artifactDep : deps) {
    DepKey key = new DepKey(artifactDep);
    Dependency dependency = depIndex.get(key);
    if (dependency == null) {
      dependency = key.createDependency();
      getModel().addDependency(dependency);
    }
    updateDependency(dependency, artifactDep);
  }
}
 
源代码2 项目: levelup-java-examples   文件: ConvertListToMap.java
@Test
public void convert_list_to_map_with_guava () {

	// create a list
	List<Movie> movies = Lists.newArrayList();
	movies.add(new Movie(1, "The Shawshank Redemption"));
	movies.add(new Movie(2, "The Godfather"));
	
	// convert list to map 
	Map<Integer,Movie> mappedMovies = Maps.uniqueIndex(movies, new Function <Movie,Integer> () {
		  public Integer apply(Movie from) {
		    return from.getRank(); // or something else
	}});
	
	logger.info(mappedMovies);
	
	assertTrue(mappedMovies.size() == 2);
	assertEquals("The Shawshank Redemption", mappedMovies.get(1).getDescription());
}
 
源代码3 项目: buck   文件: ResourceTable.java
public static ResourceTable slice(ResourceTable table, Map<Integer, Integer> countsToExtract) {
  ResTablePackage newPackage = ResTablePackage.slice(table.resPackage, countsToExtract);

  StringPool strings = table.strings;
  // Figure out what strings are used by the retained references.
  ImmutableSortedSet.Builder<Integer> stringRefs =
      ImmutableSortedSet.orderedBy(
          Comparator.comparing(strings::getString).thenComparingInt(i -> i));
  newPackage.visitStringReferences(stringRefs::add);
  ImmutableList<Integer> stringsToExtract = stringRefs.build().asList();
  ImmutableMap<Integer, Integer> stringMapping =
      Maps.uniqueIndex(
          IntStream.range(0, stringsToExtract.size())::iterator, stringsToExtract::get);

  // Extract a StringPool that contains just the strings used by the new package.
  // This drops styles.
  StringPool newStrings =
      StringPool.create(stringsToExtract.stream().map(strings::getString)::iterator);

  // Adjust the string references.
  newPackage.transformStringReferences(stringMapping::get);

  return new ResourceTable(newStrings, newPackage);
}
 
源代码4 项目: Eagle   文件: IPZonePollingJob.java
@Override
public void execute(JobExecutionContext context)
		throws JobExecutionException {
	JobDataMap jobDataMap = context.getJobDetail().getJobDataMap();
	try{
		List<IPZoneEntity> ipZones = load(jobDataMap);
		if(ipZones == null){
			LOG.warn("Ipzone information is empty");
			return;
		}
		Map<String, IPZoneEntity> map = Maps.uniqueIndex(ipZones, new Function<IPZoneEntity, String>(){
			@Override
			public String apply(IPZoneEntity input) {
				return input.getTags().get("iphost");
			}
		});
		ExternalDataCache.getInstance().setJobResult(getClass(), map);
	}catch(Exception ex){
		LOG.error("Fail loading ip zones data", ex);
	}
}
 
private PickingSlotRowsIndex(final List<PickingSlotRow> rows)
{
	rowsById = Maps.uniqueIndex(rows, PickingSlotRow::getPickingSlotRowId);

	rowId2rootRowId = rows.stream()
			.flatMap(rootRow -> streamChild2RootRowIdsRecursivelly(rootRow))
			.collect(GuavaCollectors.toImmutableMap());
}
 
源代码6 项目: incubator-gobblin   文件: HiveUtils.java
/**
 * @param client an {@link IMetaStoreClient} for the correct metastore.
 * @param table the {@link Table} for which we should get partitions.
 * @param filter an optional filter for partitions as would be used in Hive. Can only filter on String columns.
 *               (e.g. "part = \"part1\"" or "date > \"2015\"".
 * @return a map of values to {@link Partition} for input {@link Table} filtered and non-nullified.
 */
public static Map<List<String>, Partition> getPartitionsMap(IMetaStoreClient client, Table table,
    Optional<String> filter, Optional<? extends HivePartitionExtendedFilter> hivePartitionExtendedFilterOptional) throws IOException {
  return Maps.uniqueIndex(getPartitions(client, table, filter, hivePartitionExtendedFilterOptional), new Function<Partition, List<String>>() {
    @Override
    public List<String> apply(@Nullable Partition partition) {
      if (partition == null) {
        return null;
      }
      return partition.getValues();
    }
  });
}
 
源代码7 项目: verigreen   文件: JenkinsServer.java
/**
 * Get a list of all the defined jobs on the server (at the summary level)
 *
 * @return list of defined jobs (summary level, for details @see Job#details
 * @throws IOException
 */
public Map<String, Job> getJobs() throws IOException {
    List<Job> jobs = client.get("/", MainView.class).getJobs();
    return Maps.uniqueIndex(jobs, new Function<Job, String>() {
        @Override
        public String apply(Job job) {
            job.setClient(client);
            return job.getName().toLowerCase();
        }
    });
}
 
源代码8 项目: attic-aurora   文件: JobUpdaterIT.java
private void assertJobState(IJobKey job, Map<Integer, ITaskConfig> expected) {
  Iterable<IScheduledTask> tasks =
      Storage.Util.fetchTasks(storage, Query.jobScoped(job).active());

  Map<Integer, IScheduledTask> tasksByInstance =
      Maps.uniqueIndex(tasks, Tasks::getInstanceId);
  assertEquals(
      expected,
      ImmutableMap.copyOf(Maps.transformValues(tasksByInstance, Tasks::getConfig)));
}
 
private PackageableRowsIndex(final Collection<PackageableRow> rows)
{
	rowsById = Maps.uniqueIndex(rows, PackageableRow::getId);
	rowsByShipmentScheduleId = rows.stream()
			.flatMap(row -> row.getShipmentScheduleIds()
					.stream()
					.map(shipmentScheduleId -> GuavaCollectors.entry(shipmentScheduleId, row)))
			.collect(GuavaCollectors.toImmutableListMultimap());
}
 
源代码10 项目: tracecompass   文件: XmlXyDataProviderTest.java
private static void assertRows(ITmfTreeXYDataProvider<@NonNull ITmfTreeDataModel> xyProvider, Map<Long, String> tree, List<String> expectedStrings) {
    TmfModelResponse<@NonNull ITmfXyModel> rowResponse = xyProvider.fetchXY(FetchParametersUtils.selectionTimeQueryToMap(new SelectionTimeQueryFilter(1, 20, 20, tree.keySet())), null);
    assertNotNull(rowResponse);
    assertEquals(ITmfResponse.Status.COMPLETED, rowResponse.getStatus());
    ITmfXyModel rowModel = rowResponse.getModel();
    assertNotNull(rowModel);
    Collection<@NonNull ISeriesModel> series = rowModel.getSeriesData();
    ImmutableMap<Long, @NonNull ISeriesModel> data = Maps.uniqueIndex(series, ISeriesModel::getId);

    for (int i = 0; i < expectedStrings.size(); i++) {
        String expectedString = expectedStrings.get(i);
        String[] split = expectedString.split(":");
        String rowName = split[0];
        Long rowId = null;
        for (Entry<Long, String> entry : tree.entrySet()) {
            if (entry.getValue().equals(rowName)) {
                rowId = entry.getKey();
                break;
            }
        }
        assertNotNull(rowId);
        ISeriesModel row = data.get(rowId);
        assertNotNull(row);

        String[] expectedData = split[1].split(",");
        double[] actualData = row.getData();
        for (int j = 0; j < expectedData.length; j++) {
            assertTrue("Presence of data at position " + j + " for row " + rowName, actualData.length > j);
            double expectedValue = Double.parseDouble(expectedData[j]);
            assertEquals("Data at position " + j + " for row " + rowName, expectedValue, actualData[j], 0.001);
        }

    }
    assertEquals("Same number of data", expectedStrings.size(), data.size());

}
 
private Map<String, Field> getFieldMap(List<Field> fields) {
  return Maps.uniqueIndex(fields, new Function<Field, String>() {
    @Override
    public String apply(Field field) {
      if (field.isAnnotationPresent(XStreamAlias.class)) {
        return field.getAnnotation(XStreamAlias.class).value();
      }
      return field.getName();
    }
  });
}
 
源代码12 项目: nio-multipart   文件: MultipartController.java
static Map<String, FileMetadata> metadataToFileMetadataMap(final Metadata metadata){
    return Maps.uniqueIndex(metadata.getFilesMetadata(), new Function<FileMetadata, String>() {
        @Override
        public String apply(FileMetadata fileMetadata) {
            return Files.getNameWithoutExtension(fileMetadata.getFile()) + "." + Files.getFileExtension(fileMetadata.getFile());
        }
    });
}
 
/**
 * Constructor for a row that represents an HU which is already assigned to a picking slot (aka a picked HU).
 *
 * @param pickingSlotId
 * @param huId
 * @param huStorageProductId
 * @param type
 * @param processed
 * @param code
 * @param product
 * @param packingInfo
 * @param qtyCU
 * @param includedHURows
 */
@Builder(builderMethodName = "fromPickedHUBuilder", builderClassName = "FromPickedHUBuilder")
private PickingSlotRow(
		@NonNull final PickingSlotId pickingSlotId,
		@NonNull final HuId huId,
		final int huStorageProductId,
		//
		final HUEditorRowType huEditorRowType,
		final boolean processed,
		//
		final String huCode,
		final JSONLookupValue product,
		final String packingInfo,
		final BigDecimal qtyCU,
		final boolean topLevelHU,
		//
		final List<PickingSlotRow> includedHURows)
{
	pickingSlotRowId = PickingSlotRowId.ofPickedHU(pickingSlotId, huId, huStorageProductId);

	this.type = PickingSlotRowType.forPickingHuRow(huEditorRowType);
	this.processed = processed;

	documentPath = DocumentPath.rootDocumentPath(WEBUI_HU_Constants.WEBUI_HU_Window_ID, huId);

	// HU
	this.huCode = huCode;
	huProduct = product;
	huPackingInfo = packingInfo;
	huQtyCU = qtyCU;
	huTopLevel = topLevelHU;

	// Picking slot info
	pickingSlotWarehouse = null;
	pickingSlotLocatorId = null;
	pickingSlotBPartner = null;
	pickingSlotBPLocation = null;
	pickingSlotCaption = null;

	// Included rows
	this.includedHURows = includedHURows == null ? ImmutableMap.of() : Maps.uniqueIndex(includedHURows, PickingSlotRow::getPickingSlotRowId);

	this.includedViewId = null;
}
 
源代码14 项目: ganttproject   文件: GPCsvImportTest.java
private static Map<String, Task> buildTaskMap(TaskManager taskManager) {
  return Maps.uniqueIndex(Arrays.asList(taskManager.getTasks()), Task::getName);
}
 
private static DocumentFilter unwrapUsingDescriptor(
		@NonNull final JSONDocumentFilter jsonFilter,
		@NonNull final DocumentFilterDescriptor filterDescriptor)
{
	final DocumentFilter.Builder filter = DocumentFilter.builder()
			.setFilterId(jsonFilter.getFilterId())
			.setFacetFilter(filterDescriptor.isFacetFilter());

	final Map<String, JSONDocumentFilterParam> jsonParams = Maps.uniqueIndex(jsonFilter.getParameters(), JSONDocumentFilterParam::getParameterName);

	for (final DocumentFilterParamDescriptor paramDescriptor : filterDescriptor.getParameters())
	{
		final String parameterName = paramDescriptor.getParameterName();
		final JSONDocumentFilterParam jsonParam = jsonParams.get(parameterName);

		// If parameter is missing: skip it if no required, else throw exception
		if (jsonParam == null)
		{
			if (paramDescriptor.isMandatory())
			{
				throw new IllegalArgumentException("Parameter '" + parameterName + "' was not provided");
			}
			continue;
		}

		final Object value = paramDescriptor.convertValueFromJson(jsonParam.getValue());
		final Object valueTo = paramDescriptor.convertValueFromJson(jsonParam.getValueTo());

		// If there was no value/valueTo provided: skip it if no required, else throw exception
		if (value == null && valueTo == null)
		{
			if (paramDescriptor.isMandatory())
			{
				throw new IllegalArgumentException("Parameter '" + parameterName + "' has no value");
			}
			continue;
		}

		filter.addParameter(DocumentFilterParam.builder()
				.setFieldName(paramDescriptor.getFieldName())
				.setOperator(paramDescriptor.getOperator())
				.setValue(value)
				.setValueTo(valueTo)
				.build());
	}

	for (final DocumentFilterParam internalParam : filterDescriptor.getInternalParameters())
	{
		filter.addInternalParameter(internalParam);
	}

	return filter.build();
}
 
public ImmutableMap<DocumentId, Document> toImmutableMap()
{
	return Maps.uniqueIndex(documents, Document::getDocumentId);
}
 
源代码17 项目: yangtools   文件: ProcessorModuleReactor.java
ProcessorModuleReactor(final YangParser parser, final Collection<YangTextSchemaSource> modelsInProject,
    final Collection<ScannedDependency> dependencies) {
    this.parser = requireNonNull(parser);
    this.modelsInProject = Maps.uniqueIndex(modelsInProject, YangTextSchemaSource::getIdentifier);
    this.dependencies = ImmutableList.copyOf(dependencies);
}
 
源代码18 项目: bundletool   文件: BundleSharderTest.java
@Test
public void shardApexModule() throws Exception {
  ApexImages apexConfig =
      apexImages(
          targetedApexImage("apex/x86_64.x86.img", apexImageTargeting("x86_64", "x86")),
          targetedApexImage(
              "apex/x86_64.armeabi-v7a.img", apexImageTargeting("x86_64", "armeabi-v7a")),
          targetedApexImage("apex/x86_64.img", apexImageTargeting("x86_64")),
          targetedApexImage("apex/x86.armeabi-v7a.img", apexImageTargeting("x86", "armeabi-v7a")),
          targetedApexImage("apex/x86.img", apexImageTargeting("x86")),
          targetedApexImage("apex/armeabi-v7a.img", apexImageTargeting("armeabi-v7a")));
  BundleModule apexModule =
      new BundleModuleBuilder("base")
          .addFile("root/apex_manifest.json")
          .addFile("apex/x86_64.x86.img")
          .addFile("apex/x86_64.armeabi-v7a.img")
          .addFile("apex/x86_64.img")
          .addFile("apex/x86.armeabi-v7a.img")
          .addFile("apex/x86.img")
          .addFile("apex/armeabi-v7a.img")
          .setManifest(androidManifest("com.test.app"))
          .setApexConfig(apexConfig)
          .build();

  ImmutableList<ModuleSplit> shards = bundleSharder.shardApexBundle(apexModule);

  assertThat(shards).hasSize(6);
  assertThat(shards.stream().map(ModuleSplit::getSplitType).distinct().collect(toImmutableSet()))
      .containsExactly(SplitType.STANDALONE);
  assertThat(
          shards.stream()
              .map(ModuleSplit::getVariantTargeting)
              .distinct()
              .collect(toImmutableSet()))
      .containsExactly(VariantTargeting.getDefaultInstance());
  ImmutableSet<AbiAlias> x64X86Set = ImmutableSet.of(X86, X86_64);
  ImmutableSet<AbiAlias> x64ArmSet = ImmutableSet.of(ARMEABI_V7A, X86_64);
  ImmutableSet<AbiAlias> x64Set = ImmutableSet.of(X86_64);
  ImmutableSet<AbiAlias> x86ArmSet = ImmutableSet.of(ARMEABI_V7A, X86);
  ImmutableSet<AbiAlias> x86Set = ImmutableSet.of(X86);
  ImmutableSet<AbiAlias> armSet = ImmutableSet.of(ARMEABI_V7A);
  ImmutableSet<ImmutableSet<AbiAlias>> allTargeting =
      ImmutableSet.of(armSet, x86ArmSet, x64ArmSet, x86Set, x64X86Set, x64Set);
  ApkTargeting x64X86Targeting = apkMultiAbiTargetingFromAllTargeting(x64X86Set, allTargeting);
  ApkTargeting x64ArmTargeting = apkMultiAbiTargetingFromAllTargeting(x64ArmSet, allTargeting);
  ApkTargeting a64Targeting = apkMultiAbiTargetingFromAllTargeting(x64Set, allTargeting);
  ApkTargeting x86ArmTargeting = apkMultiAbiTargetingFromAllTargeting(x86ArmSet, allTargeting);
  ApkTargeting x86Targeting = apkMultiAbiTargetingFromAllTargeting(x86Set, allTargeting);
  ApkTargeting armTargeting = apkMultiAbiTargetingFromAllTargeting(armSet, allTargeting);
  ImmutableMap<ApkTargeting, ModuleSplit> splitsByTargeting =
      Maps.uniqueIndex(shards, ModuleSplit::getApkTargeting);
  assertThat(splitsByTargeting.keySet())
      .containsExactly(
          x64X86Targeting,
          x64ArmTargeting,
          a64Targeting,
          x86ArmTargeting,
          x86Targeting,
          armTargeting);
  assertThat(extractPaths(splitsByTargeting.get(x64X86Targeting).getEntries()))
      .containsExactly("root/apex_manifest.json", "apex/x86_64.x86.img");
  assertThat(extractPaths(splitsByTargeting.get(x64ArmTargeting).getEntries()))
      .containsExactly("root/apex_manifest.json", "apex/x86_64.armeabi-v7a.img");
  assertThat(extractPaths(splitsByTargeting.get(a64Targeting).getEntries()))
      .containsExactly("root/apex_manifest.json", "apex/x86_64.img");
  assertThat(extractPaths(splitsByTargeting.get(x86ArmTargeting).getEntries()))
      .containsExactly("root/apex_manifest.json", "apex/x86.armeabi-v7a.img");
  assertThat(extractPaths(splitsByTargeting.get(x86Targeting).getEntries()))
      .containsExactly("root/apex_manifest.json", "apex/x86.img");
  assertThat(extractPaths(splitsByTargeting.get(armTargeting).getEntries()))
      .containsExactly("root/apex_manifest.json", "apex/armeabi-v7a.img");
}
 
源代码19 项目: tutorials   文件: ConvertListToMapService.java
public Map<Integer, Animal> convertListWithGuava(List<Animal> list) {

        Map<Integer, Animal> map = Maps.uniqueIndex(list, Animal::getId);
        return map;
    }
 
源代码20 项目: slack-client   文件: EnumIndex.java
public EnumIndex(Class<V> enumType, Function<? super V, K> keyExtractor) {
  index = Maps.uniqueIndex(EnumSet.allOf(enumType), keyExtractor::apply);
  this.enumType = enumType;
}