Java Code Examples for java.util.LinkedHashSet#remove()

The following examples show how to use java.util.LinkedHashSet#remove() . 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: BaseMergePolicyTestCase.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/**
 * Apply a merge to a {@link SegmentInfos} instance, accumulating the number
 * of written bytes into {@code stats}.
 */
protected static SegmentInfos applyMerge(SegmentInfos infos, OneMerge merge, String mergedSegmentName, IOStats stats) throws IOException {
  LinkedHashSet<SegmentCommitInfo> scis = new LinkedHashSet<>(infos.asList());
  int newMaxDoc = 0;
  double newSize = 0;
  for (SegmentCommitInfo sci : merge.segments) {
    int numLiveDocs = sci.info.maxDoc() - sci.getDelCount();
    newSize += (double) sci.sizeInBytes() * numLiveDocs / sci.info.maxDoc() / 1024 / 1024;
    newMaxDoc += numLiveDocs;
    boolean removed = scis.remove(sci);
    assertTrue(removed);
  }
  SegmentInfos newInfos = new SegmentInfos(Version.LATEST.major);
  newInfos.addAll(scis);
  // Now add the merged segment
  newInfos.add(makeSegmentCommitInfo(mergedSegmentName, newMaxDoc, 0, newSize, IndexWriter.SOURCE_MERGE));
  stats.mergeBytesWritten += newSize * 1024 * 1024;
  return newInfos;
}
 
Example 2
Source File: EditboxPreferencePage.java    From gama with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void widgetSelected(final SelectionEvent e) {
	final int i = namesList.getSelectionIndex();
	if (i > -1) {
		final int n = categoryList.getSelectionIndex();
		if (n > -1) {
			final String key = categoryList.getItem(n);
			final String value = namesList.getItem(i);
			final LinkedHashSet<String> fNames = categoryFiles.get(key);
			fNames.remove(value);
			namesList.remove(i);
			final Object o = folder.getItem(n + 1).getData();
			if (o instanceof BoxSettingsTab) {
				((BoxSettingsTab) o).getSettings().setFileNames(new ArrayList<>(fNames));
			}
		}
	}
}
 
Example 3
Source File: ObjectiveCSourceFileGenerator.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private static void collectType(
    GeneratedType generatedType, LinkedHashSet<GeneratedType> orderedTypes,
    Map<String, GeneratedType> typeMap, LinkedHashSet<String> typeHierarchy) {
  typeHierarchy.add(generatedType.getTypeName());
  for (String superType : generatedType.getSuperTypes()) {
    GeneratedType requiredType = typeMap.get(superType);
    if (requiredType != null) {
      if (typeHierarchy.contains(superType)) {
        ErrorUtil.error("Duplicate type name found in "
            + typeHierarchy.stream().collect(Collectors.joining("->")) + "->" + superType);
        return;
      }
      collectType(requiredType, orderedTypes, typeMap, typeHierarchy);
    }
  }
  typeHierarchy.remove(generatedType.getTypeName());
  orderedTypes.add(generatedType);
}
 
Example 4
Source File: FilterResourceImpl.java    From camunda-bpm-platform with Apache License 2.0 6 votes vote down vote up
protected LinkedHashSet<String> getVariableScopeIds(HalTask... halTasks) {
  // collect scope ids
  // the ordering is important because it specifies which variables are visible from a single task
  LinkedHashSet<String> variableScopeIds = new LinkedHashSet<>();
  if (halTasks != null && halTasks.length > 0) {
    for (HalTask halTask : halTasks) {
      variableScopeIds.add(halTask.getId());
      variableScopeIds.add(halTask.getExecutionId());
      variableScopeIds.add(halTask.getProcessInstanceId());
      variableScopeIds.add(halTask.getCaseExecutionId());
      variableScopeIds.add(halTask.getCaseInstanceId());
    }
  }

  // remove null from set which was probably added due an unset id
  variableScopeIds.remove(null);

  return variableScopeIds;
}
 
Example 5
Source File: RemoveSpecifiedElementFromLinkedHashSetExample.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) {

        //create object of LinkedHashSet
        LinkedHashSet lhashSet = new LinkedHashSet();

        //add elements to LinkedHashSet object
        lhashSet.add(new Integer("1"));
        lhashSet.add(new Integer("2"));
        lhashSet.add(new Integer("3"));

        System.out.println("LinkedHashSet before removal : " + lhashSet);

    /*
      To remove an element from Java LinkedHashSet object use,
      boolean remove(Object o) method.
      This method removes an element from LinkedHashSet if it is present and returns
      true. Otherwise remove method returns false.
    */

        boolean blnRemoved = lhashSet.remove(new Integer("2"));
        System.out.println("Was 2 removed from LinkedHashSet ? " + blnRemoved);

        System.out.println("LinkedHashSet after removal : " + lhashSet);
    }
 
Example 6
Source File: FunctionTransitionUtil.java    From bazel with Apache License 2.0 6 votes vote down vote up
/**
 * Validates that function outputs exactly the set of outputs it declares. More thorough checking
 * (like type checking of output values) is done elsewhere because it requires loading. see {@link
 * StarlarkTransition#validate}
 */
private static void validateFunctionOutputsMatchesDeclaredOutputs(
    Collection<Map<String, Object>> transitions,
    StarlarkDefinedConfigTransition starlarkTransition)
    throws EvalException {
  for (Map<String, Object> transition : transitions) {
    LinkedHashSet<String> remainingOutputs =
        Sets.newLinkedHashSet(starlarkTransition.getOutputs());
    for (String outputKey : transition.keySet()) {
      if (!remainingOutputs.remove(outputKey)) {
        throw new EvalException(
            starlarkTransition.getLocationForErrorReporting(),
            String.format("transition function returned undeclared output '%s'", outputKey));
      }
    }

    if (!remainingOutputs.isEmpty()) {
      throw new EvalException(
          starlarkTransition.getLocationForErrorReporting(),
          String.format(
              "transition outputs [%s] were not defined by transition function",
              Joiner.on(", ").join(remainingOutputs)));
    }
  }
}
 
Example 7
Source File: Authenticators.java    From proarc with GNU General Public License v3.0 6 votes vote down vote up
public List<Authenticator> getAuthenticators() {
    List<Object> authenticatorIds = conf.getList(PROPERTY_AUTHENTICATORS);
    LinkedHashSet<Object> ids = new LinkedHashSet<Object>(authenticatorIds);
    // ensure the ProArc authenticator used as a last resort
    ids.remove(TYPE_PROARC);
    ids.add(TYPE_PROARC);
    ArrayList<Authenticator> authenticators = new ArrayList<Authenticator>(ids.size());
    for (Object id : ids) {
        if (TYPE_PROARC.equals(id)) {
            authenticators.add(new ProArcAuthenticator());
        } else if (TYPE_DESA.equals(id)) {
            authenticators.add(new DESAAuthenticator());
        } else {
            LOG.warning("Unknown authenticator: " + id);
        }
    }
    return authenticators;
}
 
Example 8
Source File: AnnotationSetsView.java    From gate-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Save type or remove unselected type in the preferences.
 * @param setName set name to save/remove or null for the default set
 * @param typeName type name to save/remove
 * @param selected state of the selection
 */
public void saveType(String setName, String typeName, boolean selected) {
  LinkedHashSet<String> typeList = Gate.getUserConfig().getSet(
    AnnotationSetsView.class.getName() + ".types");
  String prefix = (setName == null) ? "." : setName + ".";
  if (selected) {
    typeList.add(prefix+typeName);
  } else {
    typeList.remove(prefix+typeName);
  }
  Gate.getUserConfig().put(
    AnnotationSetsView.class.getName()+".types", typeList);
}
 
Example 9
Source File: EditorHistoryManager.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * @return a set of valid files that are in the history, oldest first.
 */
public LinkedHashSet<VirtualFile> getFileSet() {
  LinkedHashSet<VirtualFile> result = ContainerUtil.newLinkedHashSet();
  for (VirtualFile file : getFiles()) {
    // if the file occurs several times in the history, only its last occurrence counts
    result.remove(file);
    result.add(file);
  }
  return result;
}
 
Example 10
Source File: DefaultClaimSet.java    From emodb with Apache License 2.0 5 votes vote down vote up
private void removeFromExpirationQueue(Claim claim) {
    LinkedHashSet<Claim> queue = _expirationQueues.get(claim.getTtlMillis());
    if (queue != null) {
        queue.remove(claim);
    }
    // Don't remove queue from _schedule if it's empty since removing from a PriorityQueue is O(n)
}
 
Example 11
Source File: AbstractOrderExecutor.java    From oneops with Apache License 2.0 5 votes vote down vote up
protected LinkedHashSet<String> createCookbookSearchPath(String cookbookRelativePath,
    Map<String, Map<String, CmsCISimple>> cloudServices,
    String cloudName) {
  String cookbookDir = config.getCircuitDir();
  if (!cookbookRelativePath.equals("")) {
    cookbookDir = config.getCircuitDir().replace("packer",
        cookbookRelativePath);
  }

  cookbookDir += "/components/cookbooks";
  String sharedDir = config.getCircuitDir().replace("packer", "shared/cookbooks");

  LinkedHashSet<String> cookbookPaths = new LinkedHashSet<>();
  if (cloudServices != null) {
    for (String serviceName : cloudServices.keySet()) { // for each service
      CmsCISimple serviceCi = cloudServices.get(serviceName).get(cloudName);
      if (serviceCi != null) {
        String serviceClassName = serviceCi.getCiClassName();
        String serviceCookbookCircuit = getCookbookPath(serviceClassName);
        if (!serviceCookbookCircuit.equals(cookbookRelativePath)) {
          cookbookPaths.add(config.getCircuitDir().replace("packer", serviceCookbookCircuit)
              + "/components/cookbooks");
        }
      }
    }
  }
  if (cookbookPaths.size() > 0) {
    //Remove the current component's circuit from the cookbook_path so that we can add it after other circuits
    //This is to make sure the current component's circuit is higher priority in search path
    cookbookPaths.remove(cookbookDir);
  }
  cookbookPaths.add(cookbookDir);
  cookbookPaths.add(sharedDir);
  return cookbookPaths;
}
 
Example 12
Source File: InjectorFactory.java    From brave with Apache License 2.0 5 votes vote down vote up
static InjectorFunction injectorFunction(InjectorFunction existing, InjectorFunction... update) {
  if (update == null) throw new NullPointerException("injectorFunctions == null");
  LinkedHashSet<InjectorFunction> injectorFunctionSet =
      new LinkedHashSet<>(Arrays.asList(update));
  if (injectorFunctionSet.contains(null)) {
    throw new NullPointerException("injectorFunction == null");
  }
  injectorFunctionSet.remove(InjectorFunction.NOOP);
  if (injectorFunctionSet.isEmpty()) return existing;
  if (injectorFunctionSet.size() == 1) return injectorFunctionSet.iterator().next();
  return new CompositeInjectorFunction(injectorFunctionSet.toArray(new InjectorFunction[0]));
}
 
Example 13
Source File: SharedPrefUtils.java    From EFRConnect-android with Apache License 2.0 5 votes vote down vote up
public void removeDeviceFromFavorites(String device) {
    LinkedHashSet<String> favoritesDevices = getFavoritesDevices();
    favoritesDevices.remove(device);
    String json = gson.toJson(favoritesDevices);
    editor.putString(FAVORITES_DEVICES_KEY, json);
    editor.commit();
}
 
Example 14
Source File: ActuatorCustomizer.java    From GreenSummer with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    Object attribute = request.getAttribute(HandlerMapping.PRODUCIBLE_MEDIA_TYPES_ATTRIBUTE);
    if (attribute instanceof LinkedHashSet) {
        @SuppressWarnings("unchecked") LinkedHashSet<MediaType> lhs = (LinkedHashSet<MediaType>) attribute;
        if (lhs.remove(ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON)) {
            lhs.add(ActuatorMediaTypes.APPLICATION_ACTUATOR_V1_JSON);
        }
    }
    return true;
}
 
Example 15
Source File: MainLoop.java    From Concurnas with MIT License 5 votes vote down vote up
private ArrayList<SourceCodeInstance> filterSrcInstances(ArrayList<SourceCodeInstance> srcInstances){
	//remove dupes and choose instance which must be compiled if there is a choice between them
	LinkedHashSet<SourceCodeInstance> filtered = new LinkedHashSet<SourceCodeInstance>();
	for(SourceCodeInstance srci : srcInstances) {
		if(filtered.contains(srci)) {
			if(srci.mustCompile) {
				filtered.remove(srci);
				filtered.add(srci);
			}
		}else {
			filtered.add(srci);
		}
	}
	return new ArrayList<SourceCodeInstance>(filtered);
}
 
Example 16
Source File: GroupHelper.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Un-autogroups notifications that are now grouped by the app.
 */
private void maybeUngroup(StatusBarNotification sbn, boolean notificationGone, int userId) {
    List<String> notificationsToUnAutogroup = new ArrayList<>();
    boolean removeSummary = false;
    synchronized (mUngroupedNotifications) {
        Map<String, LinkedHashSet<String>> ungroupedNotificationsByUser
                = mUngroupedNotifications.get(sbn.getUserId());
        if (ungroupedNotificationsByUser == null || ungroupedNotificationsByUser.size() == 0) {
            return;
        }
        LinkedHashSet<String> notificationsForPackage
                = ungroupedNotificationsByUser.get(sbn.getPackageName());
        if (notificationsForPackage == null || notificationsForPackage.size() == 0) {
            return;
        }
        if (notificationsForPackage.remove(sbn.getKey())) {
            if (!notificationGone) {
                // Add the current notification to the ungrouping list if it still exists.
                notificationsToUnAutogroup.add(sbn.getKey());
            }
        }
        // If the status change of this notification has brought the number of loose
        // notifications to zero, remove the summary and un-autogroup.
        if (notificationsForPackage.size() == 0) {
            ungroupedNotificationsByUser.remove(sbn.getPackageName());
            removeSummary = true;
        }
    }
    if (removeSummary) {
        adjustAutogroupingSummary(userId, sbn.getPackageName(), null, false);
    }
    if (notificationsToUnAutogroup.size() > 0) {
        adjustNotificationBundling(notificationsToUnAutogroup, false);
    }
}
 
Example 17
Source File: FunctionTransitionUtil.java    From bazel with Apache License 2.0 4 votes vote down vote up
/**
 * Enter the options in buildOptions into a Starlark dictionary, and return the dictionary.
 *
 * @throws IllegalArgumentException If the method is unable to look up the value in buildOptions
 *     corresponding to an entry in optionInfoMap
 * @throws RuntimeException If the field corresponding to an option value in buildOptions is
 *     inaccessible due to Java language access control, or if an option name is an invalid key to
 *     the Starlark dictionary
 * @throws EvalException if any of the specified transition inputs do not correspond to a valid
 *     build setting
 */
static Dict<String, Object> buildSettings(
    BuildOptions buildOptions,
    Map<String, OptionInfo> optionInfoMap,
    StarlarkDefinedConfigTransition starlarkTransition)
    throws EvalException {
  LinkedHashSet<String> remainingInputs = Sets.newLinkedHashSet(starlarkTransition.getInputs());

  try (Mutability mutability = Mutability.create("build_settings")) {
    Dict<String, Object> dict = Dict.of(mutability);

    // Add native options
    for (Map.Entry<String, OptionInfo> entry : optionInfoMap.entrySet()) {
      String optionName = entry.getKey();
      String optionKey = COMMAND_LINE_OPTION_PREFIX + optionName;

      if (!remainingInputs.remove(optionKey)) {
        // This option was not present in inputs. Skip it.
        continue;
      }
      OptionInfo optionInfo = entry.getValue();

      try {
        Field field = optionInfo.getDefinition().getField();
        FragmentOptions options = buildOptions.get(optionInfo.getOptionClass());
        Object optionValue = field.get(options);

        dict.put(optionKey, optionValue == null ? Starlark.NONE : optionValue, (Location) null);
      } catch (IllegalAccessException e) {
        // These exceptions should not happen, but if they do, throw a RuntimeException.
        throw new RuntimeException(e);
      }
    }

    // Add Starlark options
    for (Map.Entry<Label, Object> starlarkOption : buildOptions.getStarlarkOptions().entrySet()) {
      if (!remainingInputs.remove(starlarkOption.getKey().toString())) {
        continue;
      }
      dict.put(starlarkOption.getKey().toString(), starlarkOption.getValue(), (Location) null);
    }

    if (!remainingInputs.isEmpty()) {
      throw new EvalException(
          starlarkTransition.getLocationForErrorReporting(),
          String.format(
              "transition inputs [%s] do not correspond to valid settings",
              Joiner.on(", ").join(remainingInputs)));
    }

    return dict;
  }
}
 
Example 18
Source File: Randomization.java    From ctsms with GNU Lesser General Public License v2.1 4 votes vote down vote up
protected final static ArrayList<RandomizationListCodeInVO> sanitizeRandomizationListCodesInput(String randomizationBlock, Collection<RandomizationListCodeInVO> codes)
		throws ServiceException {
	if (codes != null) {
		LinkedHashSet<String> textValues = new LinkedHashSet<String>();
		splitInputFieldTextValues(randomizationBlock, textValues);
		LinkedHashMap<String, RandomizationListCodeInVO> codeMap = new LinkedHashMap<String, RandomizationListCodeInVO>(codes.size());
		Iterator<RandomizationListCodeInVO> codesIt = codes.iterator();
		while (codesIt.hasNext()) {
			RandomizationListCodeInVO code = codesIt.next();
			String value = code.getCode();
			if (CommonUtil.isEmptyString(value)) {
				throw L10nUtil.initServiceException(ServiceExceptionCodes.EMPTY_RANDOMIZATION_CODE_VALUE);
			} else {
				value = (TRIM_INPUT_FIELD_TEXT_VALUE ? value.trim() : value);
				if (codeMap.containsKey(value)) {
					throw L10nUtil.initServiceException(ServiceExceptionCodes.DUPLICATE_RANDOMIZATION_CODE_VALUE, value);
				} else if (textValues.remove(value)) {
					if (TRIM_INPUT_FIELD_TEXT_VALUE) {
						code = new RandomizationListCodeInVO(code);
						code.setCode(value);
					}
					codeMap.put(value, code);
				} else {
					throw L10nUtil.initServiceException(ServiceExceptionCodes.UNKNOWN_RANDOMIZATION_CODE_VALUE, value);
				}
			}
		}
		if (textValues.size() > 0) {
			Iterator<String> it = textValues.iterator();
			StringBuilder sb = new StringBuilder();
			while (it.hasNext()) {
				if (sb.length() > 0) {
					sb.append(", ");
				}
				sb.append(it.next());
			}
			throw L10nUtil.initServiceException(ServiceExceptionCodes.MISSING_RANDOMIZATION_CODE_VALUES, sb.toString());
		} else {
			return new ArrayList<RandomizationListCodeInVO>(codeMap.values());
		}
	}
	return null;
}
 
Example 19
Source File: CoordinatorStreamSystemConsumer.java    From samza with Apache License 2.0 4 votes vote down vote up
/**
 * Read all messages from the earliest offset, all the way to the latest.
 * Currently, this method only pays attention to config messages.
 */
public void bootstrap() {
  synchronized (bootstrapLock) {
    // Make a copy so readers aren't affected while we modify the set.
    final LinkedHashSet<CoordinatorStreamMessage> bootstrappedMessages = new LinkedHashSet<>(bootstrappedStreamSet);

    log.info("Bootstrapping configuration from coordinator stream.");
    SystemStreamPartitionIterator iterator =
        new SystemStreamPartitionIterator(systemConsumer, coordinatorSystemStreamPartition);

    try {
      while (iterator.hasNext()) {
        IncomingMessageEnvelope envelope = iterator.next();
        Object[] keyArray = keySerde.fromBytes((byte[]) envelope.getKey()).toArray();
        Map<String, Object> valueMap = null;
        if (envelope.getMessage() != null) {
          valueMap = messageSerde.fromBytes((byte[]) envelope.getMessage());
        }
        CoordinatorStreamMessage coordinatorStreamMessage = new CoordinatorStreamMessage(keyArray, valueMap);
        log.debug("Received coordinator stream message: {}", coordinatorStreamMessage);
        // Remove any existing entry. Set.add() does not add if the element already exists.
        if (bootstrappedMessages.remove(coordinatorStreamMessage)) {
          log.debug("Removed duplicate message: {}", coordinatorStreamMessage);
        }
        bootstrappedMessages.add(coordinatorStreamMessage);
        if (SetConfig.TYPE.equals(coordinatorStreamMessage.getType())) {
          String configKey = coordinatorStreamMessage.getKey();
          if (coordinatorStreamMessage.isDelete()) {
            configMap.remove(configKey);
          } else {
            String configValue = new SetConfig(coordinatorStreamMessage).getConfigValue();
            configMap.put(configKey, configValue);
          }
        }
      }

      bootstrappedStreamSet = Collections.unmodifiableSet(bootstrappedMessages);
      log.debug("Bootstrapped configuration: {}", configMap);
      isBootstrapped = true;
    } catch (Exception e) {
      throw new SamzaException(e);
    }
  }
}
 
Example 20
Source File: SetSynchronizer.java    From pravega with Apache License 2.0 4 votes vote down vote up
@Override
public void process(LinkedHashSet<T> impl) {
    impl.remove(value);
}