Java Code Examples for com.google.common.collect.ArrayListMultimap

The following examples show how to use com.google.common.collect.ArrayListMultimap. These examples are extracted from open source projects. 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 Project: xtext-core   Source File: LazyLinker.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void doLinkModel(final EObject model, IDiagnosticConsumer consumer) {
	final Multimap<EStructuralFeature.Setting, INode> settingsToLink = ArrayListMultimap.create();
	final LinkingDiagnosticProducer producer = new LinkingDiagnosticProducer(consumer);
	cache.execWithoutCacheClear(model.eResource(), new IUnitOfWork.Void<Resource>() {
		@Override
		public void process(Resource state) throws Exception {
			TreeIterator<EObject> iterator = getAllLinkableContents(model);
			boolean clearAllReferencesRequired = isClearAllReferencesRequired(state);
			while (iterator.hasNext()) {
				EObject eObject = iterator.next();
				if (clearAllReferencesRequired) {
					clearReferences(eObject);
				}
				installProxies(eObject, producer, settingsToLink);
			}
		}
	});
	installQueuedLinks(settingsToLink);
}
 
Example 2
Source Project: tablesaw   Source File: Summarizer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Associates the columns to be summarized with the functions that match their type. All valid
 * combinations are used
 *
 * @param group A table slice group
 * @param selectionFunction Function that provides the filter for the having clause
 * @return A table containing a row of summarized data for each group in the table slice group
 */
private Table summarizeForHaving(
    TableSliceGroup group, Function<Table, Selection> selectionFunction) {
  List<Table> results = new ArrayList<>();

  ArrayListMultimap<String, AggregateFunction<?, ?>> reductionMultimap =
      getAggregateFunctionMultimap();

  for (String name : reductionMultimap.keys()) {
    List<AggregateFunction<?, ?>> reductions = reductionMultimap.get(name);
    Table groupTable = group.aggregate(name, reductions.toArray(new AggregateFunction<?, ?>[0]));
    groupTable = groupTable.where(selectionFunction);
    if (!groupTable.isEmpty()) {
      results.add(groupTable);
    }
  }
  return combineTables(results);
}
 
Example 3
Source Project: incubator-pinot   Source File: PqlUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testLimitDefault() throws Exception {
  MetricFunction metricFunction = new MetricFunction(MetricAggFunction.AVG, METRIC.getMetricName(), this.metricId, COLLECTION, null, null);

  TimeSpec timeSpec = new TimeSpec(METRIC.getMetricName(), TimeGranularity.fromString("1_SECONDS"), TimeSpec.SINCE_EPOCH_FORMAT);

  ThirdEyeRequest request = ThirdEyeRequest.newBuilder()
      .setMetricFunctions(Collections.singletonList(metricFunction))
      .setStartTimeInclusive(1000)
      .setEndTimeExclusive(2000)
      .setGroupBy("dimension")
      .build("ref");

  String pql = PqlUtils.getPql(request, metricFunction, ArrayListMultimap.<String, String>create(), timeSpec);

  Assert.assertEquals(pql, "SELECT AVG(metric) FROM collection WHERE  metric >= 1 AND metric < 2 GROUP BY dimension TOP 100000");
}
 
Example 4
private static Multimap<String, ReleaseNotesMessage> createNotes(
        List<ReleaseNotesMessage> breakingMessages,
        List<ReleaseNotesMessage> newFeatureMessages, List<ReleaseNotesMessage> bugMessages,
        List<ReleaseNotesMessage> miscMessages, List<ReleaseNotesMessage> newModuleMessages) {
    final Multimap<String, ReleaseNotesMessage> notes = ArrayListMultimap.create();

    if (breakingMessages != null) {
        notes.putAll(Constants.BREAKING_COMPATIBILITY_LABEL, breakingMessages);
    }
    if (newFeatureMessages != null) {
        notes.putAll(Constants.NEW_FEATURE_LABEL, newFeatureMessages);
    }
    if (bugMessages != null) {
        notes.putAll(Constants.BUG_LABEL, bugMessages);
    }
    if (miscMessages != null) {
        notes.putAll(Constants.MISCELLANEOUS_LABEL, miscMessages);
    }
    if (newModuleMessages != null) {
        notes.putAll(Constants.NEW_MODULE_LABEL, newModuleMessages);
    }

    return notes;
}
 
Example 5
/**
 * 设置首级菜单树
 *
 * @param aclDtoList
 * @return
 */
private List<AclLevelRes> aclListToTree(List<AclLevelRes> aclDtoList) {
    if (CollectionUtils.isEmpty(aclDtoList)) {
        return Lists.newArrayList();
    }
    // level -> [dept1, dept2, ...] Map<String, List<Object>>
    Multimap<String, AclLevelRes> levelDeptMap = ArrayListMultimap.create();
    List<AclLevelRes> rootList = Lists.newArrayList();

    for (AclLevelRes dto : aclDtoList) {
        levelDeptMap.put(dto.getSysAclLevel(), dto);
        if (LevelUtil.ROOT.equals(dto.getSysAclLevel())) {
            rootList.add(dto);
        }
    }
    // 按照seq从大到小排序
    rootList.sort((o1, o2) -> o2.getSysAclSeq() - o1.getSysAclSeq());
    // 递归生成树
    transformDeptTree(rootList, LevelUtil.ROOT, levelDeptMap);
    return rootList;
}
 
Example 6
Source Project: incubator-pinot   Source File: DefaultDataProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Multimap<EventSlice, EventDTO> fetchEvents(Collection<EventSlice> slices) {
  Multimap<EventSlice, EventDTO> output = ArrayListMultimap.create();
  for (EventSlice slice : slices) {
    List<Predicate> predicates = DetectionUtils.buildPredicatesOnTime(slice.getStart(), slice.getEnd());

    if (predicates.isEmpty())
      throw new IllegalArgumentException("Must provide at least one of start, or end");
    List<EventDTO> events = this.eventDAO.findByPredicate(AND(predicates));
    Iterator<EventDTO> itEvent = events.iterator();
    while (itEvent.hasNext()) {
      if (!slice.match(itEvent.next())) {
        itEvent.remove();
      }
    }

    output.putAll(slice, events);
  }
  return output;
}
 
Example 7
Source Project: hmftools   Source File: AmberSiteFactory.java    License: GNU General Public License v3.0 6 votes vote down vote up
@NotNull
public static ListMultimap<Chromosome, AmberSite> sites(@NotNull final String vcfFile) throws IOException {
    final ListMultimap<Chromosome, AmberSite> result = ArrayListMultimap.create();

    try (final AbstractFeatureReader<VariantContext, LineIterator> reader = getFeatureReader(vcfFile, new VCFCodec(), false)) {
        for (VariantContext variant : reader.iterator()) {
            if (variant.isNotFiltered()) {
                if (HumanChromosome.contains(variant.getContig())) {
                    HumanChromosome chromosome = HumanChromosome.fromString(variant.getContig());
                    result.put(chromosome,
                            ImmutableAmberSite.builder()
                                    .chromosome(variant.getContig())
                                    .position(variant.getStart())
                                    .ref(variant.getReference().getBaseString())
                                    .alt(variant.getAlternateAllele(0).getBaseString())
                                    .snpCheck(variant.hasAttribute("SNPCHECK"))
                                    .build());
                }
            }
        }
    }

    return result;
}
 
Example 8
Source Project: incubator-pinot   Source File: EntityUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testEncodeDimensionsExclusions() {
  Multimap<String, String> filters = ArrayListMultimap.create();
  filters.put("a", "A");
  filters.put("b", "!B");
  filters.put("c", "<C");
  filters.put("d", ">D");
  filters.put("e", "<=E");
  filters.put("f", ">=F");

  List<String> encoded = EntityUtils.encodeDimensions(filters);
  Assert.assertEquals(encoded.size(), 6);
  Assert.assertEquals(encoded.get(0), "a%3DA");
  Assert.assertEquals(encoded.get(1), "b!%3DB");
  Assert.assertEquals(encoded.get(2), "c%3CC");
  Assert.assertEquals(encoded.get(3), "d%3ED");
  Assert.assertEquals(encoded.get(4), "e%3C%3DE");
  Assert.assertEquals(encoded.get(5), "f%3E%3DF");
}
 
Example 9
Source Project: bazel   Source File: CcToolchainFeaturesTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a {@code Variables} configuration from a list of key/value pairs.
 *
 * <p>If there are multiple entries with the same key, the variable will be treated as sequence
 * type.
 */
private CcToolchainVariables createVariables(String... entries) {
  if (entries.length % 2 != 0) {
    throw new IllegalArgumentException(
        "createVariables takes an even number of arguments (key/value pairs)");
  }
  Multimap<String, String> entryMap = ArrayListMultimap.create();
  for (int i = 0; i < entries.length; i += 2) {
    entryMap.put(entries[i], entries[i + 1]);
  }
  CcToolchainVariables.Builder variables = CcToolchainVariables.builder();
  for (String name : entryMap.keySet()) {
    Collection<String> value = entryMap.get(name);
    if (value.size() == 1) {
      variables.addStringVariable(name, value.iterator().next());
    } else {
      variables.addStringSequenceVariable(name, ImmutableList.copyOf(value));
    }
  }
  return variables.build();
}
 
Example 10
@NotNull
private static ListMultimap<GenomePosition, StructuralVariant> cnaMap(@NotNull final Collection<StructuralVariant> variants) {
    final ListMultimap<GenomePosition, StructuralVariant> result = ArrayListMultimap.create();
    for (final StructuralVariant variant : variants) {
        final StructuralVariantLeg start = variant.start();
        result.put(GenomePositions.create(start.chromosome(), start.cnaPosition()), variant);

        @Nullable
        final StructuralVariantLeg end = variant.end();
        if (end != null) {
            result.put(GenomePositions.create(end.chromosome(), end.cnaPosition()), variant);
        }
    }

    return result;

}
 
Example 11
Source Project: 07kit   Source File: LootOverlayPlugin.java    License: GNU General Public License v3.0 6 votes vote down vote up
@Schedule(600)
public void pollLoot() {
    if (!isLoggedIn()) {
        return;
    }
    // Prepare the regex filter if required.
    checkFilter();

    // Group all loot by tile
    Multimap<Tile, Loot> tmpLootMap = ArrayListMultimap.create();
    Session.get().loot.find().distance(maximumDistance)
            .filter(acceptable -> {
                if (acceptable.getName().toLowerCase().matches(compiledFilter)) {
                    return !hideFiltered;
                }
                return filter.length() == 0 || hideFiltered;
            })
            .asList()
            .forEach(item -> {
                item.getComposite().getPrice();//force price to load
                if (item.getComposite().getPrice() >= minimumGePrice) {
                    tmpLootMap.put(item.getTile(), item);
                }
            });
    lootMap = tmpLootMap;
}
 
Example 12
Source Project: tasmo   Source File: ViewModelParser.java    License: Apache License 2.0 6 votes vote down vote up
public List<ViewBinding> parse(List<String> modelPathtrings) {
    ArrayListMultimap<String, ModelPath> viewBindings = ArrayListMultimap.create();

    for (String simpleBinding : modelPathtrings) {
        String[] class_pathId_modelPath = toStringArray(simpleBinding, "::");
        List<ModelPath> bindings = viewBindings.get(class_pathId_modelPath[0].trim());

        try {
            bindings.add(buildPath(class_pathId_modelPath[1].trim(), class_pathId_modelPath[2].trim()));
        } catch (Throwable t) {
            t.printStackTrace(System.out);
        }
    }

    List<ViewBinding> viewBindingsList = Lists.newArrayList();
    for (Map.Entry<String, Collection<ModelPath>> entry : viewBindings.asMap().entrySet()) {
        viewBindingsList.add(new ViewBinding(entry.getKey(), new ArrayList<>(entry.getValue()), false, true, null));
    }

    return viewBindingsList;
}
 
Example 13
Source Project: spring-boot-demo   Source File: RbacAuthorityService.java    License: MIT License 6 votes vote down vote up
/**
 * 获取 所有URL Mapping,返回格式为{"/test":["GET","POST"],"/sys":["GET","DELETE"]}
 *
 * @return {@link ArrayListMultimap} 格式的 URL Mapping
 */
private Multimap<String, String> allUrlMapping() {
    Multimap<String, String> urlMapping = ArrayListMultimap.create();

    // 获取url与类和方法的对应信息
    Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();

    handlerMethods.forEach((k, v) -> {
        // 获取当前 key 下的获取所有URL
        Set<String> url = k.getPatternsCondition()
                .getPatterns();
        RequestMethodsRequestCondition method = k.getMethodsCondition();

        // 为每个URL添加所有的请求方法
        url.forEach(s -> urlMapping.putAll(s, method.getMethods()
                .stream()
                .map(Enum::toString)
                .collect(Collectors.toList())));
    });

    return urlMapping;
}
 
Example 14
Source Project: bazel   Source File: AnalysisUtils.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
public static Multimap<BuildConfiguration, DependencyKey> targetsToDeps(
    Collection<TargetAndConfiguration> nodes, ConfiguredRuleClassProvider ruleClassProvider) {
  Multimap<BuildConfiguration, DependencyKey> asDeps = ArrayListMultimap.create();
  for (TargetAndConfiguration targetAndConfig : nodes) {
    ConfigurationTransition transition =
        TransitionResolver.evaluateTransition(
            targetAndConfig.getConfiguration(),
            NoTransition.INSTANCE,
            targetAndConfig.getTarget(),
            ruleClassProvider.getTrimmingTransitionFactory());
    if (targetAndConfig.getConfiguration() != null) {
      // TODO(bazel-team): support top-level aspects
      asDeps.put(
          targetAndConfig.getConfiguration(),
          DependencyKey.builder()
              .setLabel(targetAndConfig.getLabel())
              .setTransition(transition)
              .build());
    }
  }
  return asDeps;
}
 
Example 15
Source Project: incubator-pinot   Source File: PqlUtilsTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testLimit() throws Exception {
  MetricFunction metricFunction = new MetricFunction(MetricAggFunction.AVG, METRIC.getMetricName(), this.metricId, COLLECTION, null, null);

  TimeSpec timeSpec = new TimeSpec(METRIC.getMetricName(), TimeGranularity.fromString("1_SECONDS"), TimeSpec.SINCE_EPOCH_FORMAT);

  ThirdEyeRequest request = ThirdEyeRequest.newBuilder()
      .setMetricFunctions(Collections.singletonList(metricFunction))
      .setStartTimeInclusive(1000)
      .setEndTimeExclusive(2000)
      .setGroupBy("dimension")
      .setLimit(12345)
      .build("ref");

  String pql = PqlUtils.getPql(request, metricFunction, ArrayListMultimap.<String, String>create(), timeSpec);

  Assert.assertEquals(pql, "SELECT AVG(metric) FROM collection WHERE  metric >= 1 AND metric < 2 GROUP BY dimension TOP 12345");
}
 
Example 16
private ListMultimap<Class, Task> groupTasksByType(List<Task> tasks) {
    final Set<Class> taskTypes = new TreeSet<Class>(new Comparator<Class>() {
        public int compare(Class o1, Class o2) {
            return o1.getSimpleName().compareTo(o2.getSimpleName());
        }
    });
    taskTypes.addAll(collect(tasks, new Transformer<Class, Task>() {
        public Class transform(Task original) {
            return getDeclaredTaskType(original);
        }
    }));

    ListMultimap<Class, Task> tasksGroupedByType = ArrayListMultimap.create();
    for (final Class taskType : taskTypes) {
        tasksGroupedByType.putAll(taskType, filter(tasks, new Spec<Task>() {
            public boolean isSatisfiedBy(Task element) {
                return getDeclaredTaskType(element).equals(taskType);
            }
        }));
    }
    return tasksGroupedByType;
}
 
Example 17
public Map<DBIdentity, UserDiff> diffState() throws SQLException, MitroServletException {
  // get the new state
  Multimap<Integer, Integer> newState = ArrayListMultimap.create();
  addUserDataToSet(userIdToSecretIds.keySet(), newState);
  
  Map<DBIdentity, UserDiff> rval = Maps.newHashMap();
  for (Integer uid : userIdToSecretIds.keySet()) {
    Set<Integer> preSecrets = Sets.newHashSet(userIdToSecretIds.get(uid));
    Set<Integer> postSecrets = Sets.newHashSet(newState.get(uid));
    UserDiff ud = new UserDiff();
    ud.removedSecrets = Sets.difference(preSecrets, postSecrets);
    ud.newSecrets = Sets.difference(postSecrets, preSecrets);
    if (ud.removedSecrets.isEmpty() && ud.newSecrets.isEmpty()) {
      continue;
    }

    // TODO: optimize this to one query instead of n queries.
    DBIdentity id = manager.identityDao.queryForId(uid);
    ud.userName = id.getName();
    rval.put(id, ud);
  }
  return rval;
}
 
Example 18
Source Project: cloudbreak   Source File: UserSyncServiceTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void testRemoveUsersFromGroupsNullMembersInResponse() throws Exception {
    Multimap<String, String> groupMapping = setupGroupMapping(1, 1);

    FreeIpaClient freeIpaClient = mock(FreeIpaClient.class);
    Group removeResponseGroup = mock(Group.class, RETURNS_DEEP_STUBS);
    RPCResponse<Group> mockRemoveResponse = mock(RPCResponse.class);
    when(mockRemoveResponse.getResult()).thenReturn(removeResponseGroup);
    // FreeIPA returns null when group is empty
    when(removeResponseGroup.getMemberUser()).thenReturn(null);
    when(freeIpaClient.groupRemoveMembers(any(), any())).thenReturn(mockRemoveResponse);
    Multimap<String, String> warnings = ArrayListMultimap.create();

    underTest.removeUsersFromGroups(freeIpaClient, groupMapping, warnings::put);

    assertTrue(warnings.isEmpty());
}
 
Example 19
Source Project: calcite   Source File: DruidAdapter2IT.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testMetadataColumns() throws Exception {
  sql("values 1")
      .withConnection(c -> {
        try {
          final DatabaseMetaData metaData = c.getMetaData();
          final ResultSet r =
              metaData.getColumns(null, null, "foodmart", null);
          Multimap<String, Boolean> map = ArrayListMultimap.create();
          while (r.next()) {
            map.put(r.getString("TYPE_NAME"), true);
          }
          if (CalciteSystemProperty.DEBUG.value()) {
            System.out.println(map);
          }
          // 1 timestamp, 2 float measure, 1 int measure, 88 dimensions
          assertThat(map.keySet().size(), is(4));
          assertThat(map.values().size(), is(92));
          assertThat(map.get("TIMESTAMP(0) NOT NULL").size(), is(1));
          assertThat(map.get("DOUBLE").size(), is(2));
          assertThat(map.get("BIGINT").size(), is(1));
          assertThat(map.get(VARCHAR_TYPE).size(), is(88));
        } catch (SQLException e) {
          throw TestUtil.rethrow(e);
        }
      });
}
 
Example 20
Source Project: bazel   Source File: ImmutableSortedKeyListMultimapTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void copyOfEmpty() {
  ListMultimap<String, Integer> input = ArrayListMultimap.create();
  Multimap<String, Integer> multimap = ImmutableSortedKeyListMultimap.copyOf(input);
  assertThat(input).isEqualTo(multimap);
  assertThat(multimap).isEqualTo(input);
}
 
Example 21
Source Project: attic-apex-malhar   Source File: AbstractPojoJoin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public List<Multimap<List<Object>, Object>> defaultAccumulatedValue()
{
  List<Multimap<List<Object>, Object>> accu = new ArrayList<>();
  for (int i = 0; i < 2; i++) {
    Multimap<List<Object>, Object> mMap = ArrayListMultimap.create();
    accu.add(mMap);
  }
  return accu;
}
 
Example 22
/**
 * Get all Response headers as a map of name to list of values.
 * A value may be null.
 *
 * @return Map, may be empty but not null.
 */
public Multimap<String, String> getResponseHeaders() {
  if (this.lastresponse == null)
    return ImmutableMultimap.of();

  ArrayListMultimap<String, String> multimap = ArrayListMultimap.create();
  for (Header header : this.lastresponse.getAllHeaders()) {
    for (HeaderElement element : header.getElements()) {
      multimap.put(element.getName(), element.getValue());
    }
  }
  return multimap;
}
 
Example 23
private ListMultimap<String, OptionDescriptor> groupDescriptorsByName(List<OptionDescriptor> allOptions) {
    ListMultimap<String, OptionDescriptor> optionsGroupedByName = ArrayListMultimap.create();
    for (final OptionDescriptor option : allOptions) {
        optionsGroupedByName.put(option.getName(), option);
    }
    return optionsGroupedByName;
}
 
Example 24
Source Project: onos   Source File: InstallCoordinator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Generates a mapping for installable Intents to installers.
 *
 * @param intentData the Intent data which contains installable Intents
 * @return the mapping for installable Intents to installers
 */
private ArrayListMultimap<IntentInstaller, Intent> getInstallers(IntentData intentData) {
    ArrayListMultimap<IntentInstaller, Intent> intentInstallers = ArrayListMultimap.create();
    intentData.installables().forEach(intent -> {
        IntentInstaller installer = installerRegistry.getInstaller(intent.getClass());
        if (installer != null) {
            intentInstallers.put(installer, intent);
        } else {
            log.warn(INSTALLER_NOT_FOUND, intent);
        }
    });
    return intentInstallers;
}
 
Example 25
Source Project: hmftools   Source File: Multimaps.java    License: GNU General Public License v3.0 5 votes vote down vote up
@NotNull
public static <T extends GenomePosition> ListMultimap<Chromosome, T> fromPositions(@NotNull final Collection<T> regions) {
    final ListMultimap<Chromosome, T> result = ArrayListMultimap.create();
    for (T region : regions) {
        if (HumanChromosome.contains(region.chromosome())) {
            result.put(HumanChromosome.fromString(region.chromosome()), region);
        }
    }

    return result;
}
 
Example 26
Source Project: bazel   Source File: SkyQueryEnvironment.java    License: Apache License 2.0 5 votes vote down vote up
public static Multimap<SkyKey, SkyKey> makePackageKeyToTargetKeyMap(Iterable<SkyKey> keys) {
  Multimap<SkyKey, SkyKey> packageKeyToTargetKeyMap = ArrayListMultimap.create();
  for (SkyKey key : keys) {
    Label label = SKYKEY_TO_LABEL.apply(key);
    if (label == null) {
      continue;
    }
    packageKeyToTargetKeyMap.put(PackageValue.key(label.getPackageIdentifier()), key);
  }
  return packageKeyToTargetKeyMap;
}
 
Example 27
Source Project: xian   Source File: UnitMdBuilderHandler.java    License: Apache License 2.0 5 votes vote down vote up
private Multimap<String, UnitProxy> buildUnits() {
    Multimap<String, UnitProxy> groupedUnits = ArrayListMultimap.create();
    List<String> unitFullNames = UnitDiscovery.singleton.queryForNames();
    for (String unitFullName : unitFullNames) {
        UnitProxy unitProxy = UnitDiscovery.singleton.newestDefinition(unitFullName);
        if (unitProxy != null)
            groupedUnits.put(unitProxy.getGroup().getName(), unitProxy);
    }
    return groupedUnits;
}
 
Example 28
Source Project: artemis   Source File: RegistryRepository.java    License: Apache License 2.0 5 votes vote down vote up
public ListMultimap<Service, Lease<Instance>> getLeases(Collection<String> serviceIds, LeaseManager<Instance> leaseManager) {
    ListMultimap<Service, Lease<Instance>> leases = ArrayListMultimap.create();
    for (String serviceId : serviceIds) {
        Service service = getApplicationInternal(serviceId);
        leases.putAll(service, getLeases(serviceId, leaseManager));
    }

    return leases;
}
 
Example 29
Source Project: momo-cloud-permission   Source File: DataDictServiceImpl.java    License: Apache License 2.0 5 votes vote down vote up
private List<DataDictTreeRes> dictListToTree(List<DataDictTreeRes> dictTreeList) {
    Multimap<String, DataDictTreeRes> levelDeptMap = ArrayListMultimap.create();
    List<DataDictTreeRes> rootList = Lists.newArrayList();
    for (DataDictTreeRes dataDictTreeRes : dictTreeList) {
        levelDeptMap.put(dataDictTreeRes.getSysDictCodeLevel(), dataDictTreeRes);
        if (LevelUtil.ROOT.equals(dataDictTreeRes.getSysDictCodeLevel())) {
            rootList.add(dataDictTreeRes);
        }
    }
    // 按照seq从大到小排序
    rootList.sort((o1, o2) -> o2.getSysDictCodeSeq() - o1.getSysDictCodeSeq());
    // 递归生成树
    transformDictTree(rootList, LevelUtil.ROOT, levelDeptMap);
    return rootList;
}
 
Example 30
Source Project: redis-manager   Source File: InstallationTemplate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param installationParam
 */
public void buildMachineRedisNodeMap(InstallationParam installationParam) {
    Multimap<Machine, RedisNode> machineAndRedisNode = ArrayListMultimap.create();
    List<Machine> machineList = installationParam.getMachineList();
    List<RedisNode> allRedisNodes = installationParam.getRedisNodeList();
    for (Machine machine : machineList) {
        for (RedisNode redisNode : allRedisNodes) {
            if (Objects.equals(machine.getHost(), redisNode.getHost())) {
                machineAndRedisNode.put(machine, redisNode);
            }
        }
    }
    installationParam.setMachineAndRedisNode(machineAndRedisNode);
}