Java Code Examples for com.google.common.collect.Maps#uniqueIndex()

The following examples show how to use com.google.common.collect.Maps#uniqueIndex() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Pom.java    From buck with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example 2
Source File: ConvertListToMap.java    From levelup-java-examples with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 3
Source File: IPZonePollingJob.java    From Eagle with Apache License 2.0 6 votes vote down vote up
@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);
	}
}
 
Example 4
Source File: ResourceTable.java    From buck with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 5
Source File: PickingSlotRowsCollection.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
private PickingSlotRowsIndex(final List<PickingSlotRow> rows)
{
	rowsById = Maps.uniqueIndex(rows, PickingSlotRow::getPickingSlotRowId);

	rowId2rootRowId = rows.stream()
			.flatMap(rootRow -> streamChild2RootRowIdsRecursivelly(rootRow))
			.collect(GuavaCollectors.toImmutableMap());
}
 
Example 6
Source File: HiveUtils.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * @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();
    }
  });
}
 
Example 7
Source File: MultipartController.java    From nio-multipart with Apache License 2.0 5 votes vote down vote up
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());
        }
    });
}
 
Example 8
Source File: JenkinsServer.java    From verigreen with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
        }
    });
}
 
Example 9
Source File: JobUpdaterIT.java    From attic-aurora with Apache License 2.0 5 votes vote down vote up
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)));
}
 
Example 10
Source File: WxPayOrderNotifyResultConverter.java    From weixin-java-tools with Apache License 2.0 5 votes vote down vote up
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();
    }
  });
}
 
Example 11
Source File: PackageableRowsIndex.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 5 votes vote down vote up
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());
}
 
Example 12
Source File: XmlXyDataProviderTest.java    From tracecompass with Eclipse Public License 2.0 5 votes vote down vote up
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());

}
 
Example 13
Source File: EnumIndex.java    From slack-client with Apache License 2.0 4 votes vote down vote up
public EnumIndex(Class<V> enumType, Function<? super V, K> keyExtractor) {
  index = Maps.uniqueIndex(EnumSet.allOf(enumType), keyExtractor::apply);
  this.enumType = enumType;
}
 
Example 14
Source File: PickingSlotRow.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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;
}
 
Example 15
Source File: ConvertListToMapService.java    From tutorials with MIT License 4 votes vote down vote up
public Map<Integer, Animal> convertListWithGuava(List<Animal> list) {

        Map<Integer, Animal> map = Maps.uniqueIndex(list, Animal::getId);
        return map;
    }
 
Example 16
Source File: BundleSharderTest.java    From bundletool with Apache License 2.0 4 votes vote down vote up
@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");
}
 
Example 17
Source File: ProcessorModuleReactor.java    From yangtools with Eclipse Public License 1.0 4 votes vote down vote up
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);
}
 
Example 18
Source File: OrderedDocumentsList.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 4 votes vote down vote up
public ImmutableMap<DocumentId, Document> toImmutableMap()
{
	return Maps.uniqueIndex(documents, Document::getDocumentId);
}
 
Example 19
Source File: JSONDocumentFilter.java    From metasfresh-webui-api-legacy with GNU General Public License v3.0 4 votes vote down vote up
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();
}
 
Example 20
Source File: GPCsvImportTest.java    From ganttproject with GNU General Public License v3.0 4 votes vote down vote up
private static Map<String, Task> buildTaskMap(TaskManager taskManager) {
  return Maps.uniqueIndex(Arrays.asList(taskManager.getTasks()), Task::getName);
}