Java Code Examples for java.util.HashSet.contains()

The following are Jave code examples for showing how to use contains() of the java.util.HashSet class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: springreplugin   File: Builder.java   View Source Code Vote up 7 votes
private static void deleteUnknownLibs(Context context, PxAll all) {
    HashSet<String> names = new HashSet<>();
    for (PluginInfo p : all.getPlugins()) {
        names.add(p.getNativeLibsDir().getName());
    }

    File dir = context.getDir(AppConstant.LOCAL_PLUGIN_DATA_LIB_DIR, 0);
    File files[] = dir.listFiles();
    if (files != null) {
        for (File f : files) {
            if (names.contains(f.getName())) {
                continue;
            }
            if (LOG) {
                LogDebug.d(PLUGIN_TAG, "delete unknown libs=" + f.getAbsolutePath());
            }
            try {
                FileUtils.forceDelete(f);
            } catch (IOException e) {
                if (LOG) {
                    LogDebug.d(PLUGIN_TAG, "can't delete unknown libs=" + f.getAbsolutePath(), e);
                }
            }
        }
    }
}
 
Example 2
Project: AOSP-Kayboard-7.1.2   File: SuggestedWords.java   View Source Code Vote up 6 votes
public static ArrayList<SuggestedWordInfo> getTypedWordAndPreviousSuggestions(
        @Nonnull final SuggestedWordInfo typedWordInfo,
        @Nonnull final SuggestedWords previousSuggestions) {
    final ArrayList<SuggestedWordInfo> suggestionsList = new ArrayList<>();
    final HashSet<String> alreadySeen = new HashSet<>();
    suggestionsList.add(typedWordInfo);
    alreadySeen.add(typedWordInfo.mWord);
    final int previousSize = previousSuggestions.size();
    for (int index = 1; index < previousSize; index++) {
        final SuggestedWordInfo prevWordInfo = previousSuggestions.getInfo(index);
        final String prevWord = prevWordInfo.mWord;
        // Filter out duplicate suggestions.
        if (!alreadySeen.contains(prevWord)) {
            suggestionsList.add(prevWordInfo);
            alreadySeen.add(prevWord);
        }
    }
    return suggestionsList;
}
 
Example 3
Project: lams   File: Operations.java   View Source Code Vote up 6 votes
/**
 * Returns the longest string that is a prefix of all accepted strings and
 * visits each state at most once.  The automaton must be deterministic.
 * 
 * @return common prefix
 */
public static String getCommonPrefix(Automaton a) {
  if (a.isDeterministic() == false) {
    throw new IllegalArgumentException("input automaton must be deterministic");
  }
  StringBuilder b = new StringBuilder();
  HashSet<Integer> visited = new HashSet<>();
  int s = 0;
  boolean done;
  Transition t = new Transition();
  do {
    done = true;
    visited.add(s);
    if (a.isAccept(s) == false && a.getNumTransitions(s) == 1) {
      a.getTransition(s, 0, t);
      if (t.min == t.max && !visited.contains(t.dest)) {
        b.appendCodePoint(t.min);
        s = t.dest;
        done = false;
      }
    }
  } while (!done);

  return b.toString();
}
 
Example 4
Project: uPMT   File: Utils.java   View Source Code Vote up 6 votes
public static boolean checkRecovery() {
	HashSet<String> projectNames = loadProjectsNames();
	boolean ret = false;
	
	if(projectNames.isEmpty()){
		// For debug purposes
		System.out.println("No projects to load");
	}else{
		System.out.println("Loading projects");
		for (String s : projectNames) {
			if(s.contains(Projet.FORMAT)) {
				if(projectNames.contains(Projet.RECOVERY+s)) {
					ret=true;
					break;
				}
			}
		}
	}
	return ret;
}
 
Example 5
Project: SkyDocs   File: DocsProject.java   View Source Code Vote up 6 votes
/**
 * Loads pages from the specified directory.
 * 
 * @param directory The directory.
 * @param destinations Already added pages destinations.
 * 
 * @return A set of files that are not going to be copied because they already exist in the destination.
 * 
 * @throws LoadException If the specified file is not a directory.
 */

private final HashSet<String> loadPages(final File directory, final HashSet<String> destinations) throws LoadException {
	if(!directory.isDirectory()) {
		throw new LoadException("The file \"" + directory + "\" is not a directory.");
	}
	final HashSet<String> alreadyExist = new HashSet<String>();
	for(final File child : directory.listFiles()) {
		if(child.isDirectory()) {
			loadPages(child, destinations);
			continue;
		}
		if(FilenameUtils.getExtension(child.getName()).equalsIgnoreCase("md")) {
			final DocsPage page = new DocsPage(this, child);
			final String path = page.getBuildDestinationPath();
			if(destinations.contains(path)) {
				alreadyExist.add(path);
				continue;
			}
			destinations.add(path);
			addPages(page);
		}
	}
	return alreadyExist;
}
 
Example 6
Project: AndroidMuseumBleManager   File: BluetoothUuidCompat.java   View Source Code Vote up 6 votes
/**
 * Returns true if there any common ParcelUuids in uuidA and uuidB.
 *
 * @param uuidA - List of ParcelUuids
 * @param uuidB - List of ParcelUuids
 */
public static boolean containsAnyUuid(ParcelUuid[] uuidA, ParcelUuid[] uuidB) {
    if (uuidA == null && uuidB == null) return true;

    if (uuidA == null) {
        return uuidB.length == 0;
    }

    if (uuidB == null) {
        return uuidA.length == 0;
    }

    HashSet<ParcelUuid> uuidSet = new HashSet<>(Arrays.asList(uuidA));
    for (ParcelUuid uuid : uuidB) {
        if (uuidSet.contains(uuid)) return true;
    }
    return false;
}
 
Example 7
Project: javaide   File: LocalSdkParser.java   View Source Code Vote up 5 votes
/**
 * The sdk manager only lists valid addons. However here we also want to find "broken"
 * addons, i.e. addons that failed to load for some reason.
 * <p/>
 * Find any other sub-directories under the /add-ons root that hasn't been visited yet
 * and assume they contain broken addons.
 */
private void scanMissingAddons(SdkManager sdkManager,
        HashSet<File> visited,
        ArrayList<Package> packages,
        ILogger log) {
    File addons = new File(new File(sdkManager.getLocation()), SdkConstants.FD_ADDONS);

    for (File dir : listFilesNonNull(addons)) {
        if (dir.isDirectory() && !visited.contains(dir)) {
            Pair<Map<String, String>, String> infos =
                parseAddonProperties(dir, sdkManager.getTargets(), log);
            Properties sourceProps =
                parseProperties(new File(dir, SdkConstants.FN_SOURCE_PROP));

            Map<String, String> addonProps = infos.getFirst();
            String error = infos.getSecond();
            try {
                Package pkg = AddonPackage.createBroken(dir.getAbsolutePath(),
                                                        sourceProps,
                                                        addonProps,
                                                        error);
                packages.add(pkg);
                visited.add(dir);
            } catch (Exception e) {
                log.error(e, null);
            }
        }
    }
}
 
Example 8
Project: Helpers   File: ParserNode.java   View Source Code Vote up 5 votes
private BigDecimal eval(Interpreter interpreter, HashMap<String, BigDecimal> arguments, HashSet<String> reserved) throws SyntaxException, ArithmeticException, StackOverflowError {
    if (value == null) {
        BigDecimal l = left.eval(interpreter, arguments);
        BigDecimal r = right.eval(interpreter, arguments);
        switch (operator) {
            case '-': return l.subtract(r);
            case '+': return l.add(r);
            case '*': return l.multiply(r);
            case '%': return l.remainder(r);
            case '/': return l.divide(r, interpreter.getInternalRounding(), RoundingMode.HALF_UP);
            case '^': return l.pow(r.intValue());
        }
    }
    if (reserved.contains(value))
        throw new SyntaxException("Variable '" + value + "' is reserved");
    if(arguments.containsKey(value))
        return arguments.get(value);

    HashMap<String, BigDecimal> variables = interpreter.getVariables();
    if(variables.containsKey(value))
        return variables.get(value);
    if (value.contains("(")) {
        HashMap<String, Function> functions = interpreter.getFunctions();
        String name = value.split("\\(")[0];
        if(!functions.containsKey(name)) throw new SyntaxException("Function '" + name + "' not defined");
        String args = value.substring(name.length() + 1, value.length() - 1);
        return functions.get(name).eval(interpreter, arguments, args);
    }
    if(value.matches("[0-9]+(\\.[0-9]*)?"))
        return new BigDecimal(value);
    throw new SyntaxException("Variable '" + value + "' not defined");
}
 
Example 9
Project: FuzzDroid   File: SourceConstantFuzzer.java   View Source Code Vote up 5 votes
private Object chooseNewValue(HashSet<Object> usedValues, Object[] allValues) {

		Object newValue = null;

		// if we do not have any constant values for the requested type, we
		// return null
		if (null == allValues || allValues.length == 0) {
			return null;
		}

		// if we havent used any values, just pick one
		if (null == usedValues || usedValues.size() == 0) {
			newValue = allValues[DeterministicRandom.theRandom.nextInt(allValues.length)];
		} else {
			if (!RETURN_DUPLICATES) {
				// if all values have been tried -> return null == out of values
				if (usedValues.size() == allValues.length) {
					return null;
				}

				do {
					newValue = allValues[DeterministicRandom.theRandom.nextInt(allValues.length)];
				} while (usedValues.contains(newValue));
			} else {
				// just choose one and dont care about duplicates
				newValue = allValues[DeterministicRandom.theRandom.nextInt(allValues.length)];
			}

		}

		return newValue;
	}
 
Example 10
Project: ramus   File: SectorRefactor.java   View Source Code Vote up 5 votes
/**
 * Додає в масив сектори відображення, які пов’язані між собою одним потоком
 * і знаходяться на одному функціональному блоці.
 *
 * @param sector - сектор, для якого будуть знайдені пов’язані.
 * @param v      Вектор в який будуть додані сектори відображення.
 */

public void getStreamedSectors(final PaintSector sector, final HashSet v) {
    getStreamedSectors(sector.getSector(), sector.getStart(), v, true);
    getStreamedSectors(sector.getSector(), sector.getEnd(), v, true);
    if (!v.contains(sector))
        v.add(sector);
}
 
Example 11
Project: AgentWorkbench   File: NetworkModel.java   View Source Code Vote up 5 votes
/**
 * Removes all network components if not in the specified list.
 * @param networkComponentsToKeep the network components to keep when deleting network components
 */
public HashSet<NetworkComponent> removeNetworkComponentsInverse(HashSet<NetworkComponent> networkComponentsToKeep) {
	HashSet<NetworkComponent> removed = new HashSet<NetworkComponent>();
	HashSet<String> networkComponentIDs = this.getNetworkComponentsIDs(networkComponentsToKeep);
	for (NetworkComponent networkComponent : new ArrayList<NetworkComponent>(this.networkComponents.values())) {
		if (networkComponentIDs.contains(networkComponent.getId())==false) {
			removeNetworkComponent(networkComponent, true, false);
			removed.add(networkComponent);
		}
	}
	this.refreshGraphElements();
	return removed;
}
 
Example 12
Project: FlickLauncher   File: ItemInfoMatcher.java   View Source Code Vote up 5 votes
public static ItemInfoMatcher ofShortcutKeys(final HashSet<ShortcutKey> keys) {
    return new ItemInfoMatcher() {
        @Override
        public boolean matches(ItemInfo info, ComponentName cn) {
            return info.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT &&
                    keys.contains(ShortcutKey.fromShortcutInfo((ShortcutInfo) info));
        }
    };
}
 
Example 13
Project: rapidminer   File: DatabaseDataSource.java   View Source Code Vote up 5 votes
void configureMetaData() throws DataSetException {
    try {
        ResultSetMetaData e = this.getCachedResultSet().getMetaData();
        LinkedList columnNames = new LinkedList();
        LinkedList columnTypes = new LinkedList();
        HashSet usedNames = new HashSet();

        for(int columnIndex = 1; columnIndex <= e.getColumnCount(); ++columnIndex) {
            String dbColumnName = e.getColumnLabel(columnIndex);
            String columnName = dbColumnName;
            int valueType;
            if(usedNames.contains(dbColumnName)) {
                valueType = 1;

                do {
                    columnName = dbColumnName + "_" + valueType;
                    ++valueType;
                } while(usedNames.contains(columnName));
            }

            usedNames.add(columnName);
            columnNames.add(columnName);
            valueType = DatabaseHandler.getRapidMinerTypeIndex(e.getColumnType(columnIndex));
            columnTypes.add(ResultSetAdapterUtils.transformValueType(valueType));
        }

        this.metaData = new DefaultDataSetMetaData(columnNames, columnTypes);
    } catch (SQLException var9) {
        throw new DataSetException(var9.getMessage(), var9);
    }
}
 
Example 14
Project: ramus   File: Table.java   View Source Code Vote up 5 votes
public void removeDublicates() {
    HashSet<RowArrayHolder> arrayHolders = new HashSet<RowArrayHolder>();

    List<Row[]> newRows = new ArrayList<Row[]>();

    for (Row[] rows : this.rows) {
        RowArrayHolder holder = new RowArrayHolder(rows);
        if (!arrayHolders.contains(holder)) {
            arrayHolders.add(holder);
            newRows.add(rows);
        }
    }
    rows = newRows;
}
 
Example 15
Project: FacetExtract   File: iInherit.java   View Source Code Vote up 5 votes
@SafeVarargs
public static HashSet<String> mergeHashSet(HashSet<String>... list) {
	HashSet<String> mergedHashSet = new HashSet<>();
	for (HashSet<String> hashSet : list) {
		for(String str : hashSet)
			if(!mergedHashSet.contains(str))
				mergedHashSet.add(str);
	}
	return mergedHashSet;
}
 
Example 16
Project: bake_it   File: Retrieve.java   View Source Code Vote up 5 votes
public static String asString(HashSet<String> relevantRecipeNames, ArrayList<Recipe> allRecipes){
    //TODO: store recipes in hash instead
    StringBuilder recipes = new StringBuilder();
    for(Recipe recipe:allRecipes){
        if(relevantRecipeNames.contains(recipe.getName())){
            recipe.print(false);
            recipes.append(recipe.all());
        }
    }
    return recipes.toString();
}
 
Example 17
Project: OpenJSharp   File: ObjectStreamClass.java   View Source Code Vote up 4 votes
private ClassDataSlot[] getClassDataLayout0()
    throws InvalidClassException
{
    ArrayList<ClassDataSlot> slots = new ArrayList<>();
    Class<?> start = cl, end = cl;

    // locate closest non-serializable superclass
    while (end != null && Serializable.class.isAssignableFrom(end)) {
        end = end.getSuperclass();
    }

    HashSet<String> oscNames = new HashSet<>(3);

    for (ObjectStreamClass d = this; d != null; d = d.superDesc) {
        if (oscNames.contains(d.name)) {
            throw new InvalidClassException("Circular reference.");
        } else {
            oscNames.add(d.name);
        }

        // search up inheritance hierarchy for class with matching name
        String searchName = (d.cl != null) ? d.cl.getName() : d.name;
        Class<?> match = null;
        for (Class<?> c = start; c != end; c = c.getSuperclass()) {
            if (searchName.equals(c.getName())) {
                match = c;
                break;
            }
        }

        // add "no data" slot for each unmatched class below match
        if (match != null) {
            for (Class<?> c = start; c != match; c = c.getSuperclass()) {
                slots.add(new ClassDataSlot(
                    ObjectStreamClass.lookup(c, true), false));
            }
            start = match.getSuperclass();
        }

        // record descriptor/class pairing
        slots.add(new ClassDataSlot(d.getVariantFor(match), true));
    }

    // add "no data" slot for any leftover unmatched classes
    for (Class<?> c = start; c != end; c = c.getSuperclass()) {
        slots.add(new ClassDataSlot(
            ObjectStreamClass.lookup(c, true), false));
    }

    // order slots from superclass -> subclass
    Collections.reverse(slots);
    return slots.toArray(new ClassDataSlot[slots.size()]);
}
 
Example 18
Project: parabuild-ci   File: FindBugs.java   View Source Code Vote up 4 votes
/**
 * Process -bugCategories option.
 * @param categories comma-separated list of bug categories
 * @return Set of categories to be used
 */
private static Set<String> handleBugCategories(String categories) {
	// Parse list of bug categories
	HashSet<String> categorySet = new HashSet<String>();
	StringTokenizer tok = new StringTokenizer(categories, ",");
	while (tok.hasMoreTokens()) {
		categorySet.add(tok.nextToken());
	}

	// Enable only those detectors that can emit those categories
	// (and the ones that produce unknown bug patterns, just to be safe).
	// Skip disabled detectors, though.
	for (Iterator<DetectorFactory> i = DetectorFactoryCollection.instance().factoryIterator(); i.hasNext();) {
		DetectorFactory factory = i.next();
		if (!factory.isEnabled())
			continue;
		Collection<BugPattern> reported = factory.getReportedBugPatterns();
		boolean enable = false;
		if (reported.isEmpty()) {
			// Don't know what bug patterns are produced by this detector
			if (DEBUG) System.out.println("Unknown bug patterns for " + factory.getShortName());
			enable = true;
		} else {
			for (Iterator<BugPattern> j = reported.iterator(); j.hasNext();) {
				BugPattern bugPattern = j.next();
				if (categorySet.contains(bugPattern.getCategory())) {
					if (DEBUG)
						System.out.println("MATCH ==> " + categorySet +
						        " -- " + bugPattern.getCategory());
					enable = true;
					break;
				}
			}
		}
		if (DEBUG && enable) {
			System.out.println("Enabling " + factory.getShortName());
		}
		factory.setEnabled(enable);
	}

	return categorySet;
}
 
Example 19
Project: s-store   File: TPCCLoader.java   View Source Code Vote up 4 votes
/** generate replicated tables, ITEM and CUSTOMER_NAME. */
public void makeItems(int itemStart, int itemFinish) {
    // create ITEMS here to reduce memory consumption
    VoltTable items = new VoltTable(new VoltTable.ColumnInfo("I_ID", VoltType.INTEGER),
                                    new VoltTable.ColumnInfo("I_IM_ID", VoltType.INTEGER),
                                    new VoltTable.ColumnInfo("I_NAME", VoltType.STRING),
                                    new VoltTable.ColumnInfo("I_PRICE", VoltType.FLOAT),
                                    new VoltTable.ColumnInfo("I_DATA", VoltType.STRING));
    
    
    
    // items.ensureRowCapacity(parameters.items);
    // items.ensureStringCapacity(parameters.items * 96);
    // Select 10% of the rows to be marked "original"
    if (debug.val)
        LOG.debug(String.format("Loading replicated ITEM table [tuples=%d]", m_parameters.num_items));
    HashSet<Integer> originalRows = selectUniqueIds(m_parameters.num_items / 10, 1, m_parameters.num_items);
    for (int i = itemStart; i < itemFinish; ++i) {
        // if we're on a 10% boundary, print out some nice status info
        // if (i % (m_parameters.items / 10) == 0)
        // System.err.printf("   %d%%\n", (i * 100) /
        // m_parameters.items);

        boolean original = originalRows.contains(i);
        generateItem(items, i, original);
        
        // Items! Sail yo ho!
        if (items.getRowCount() == replicated_batch_size) {
            if (debug.val)
                LOG.debug(String.format("Loading replicated ITEM table [tuples=%d/%d]", i, m_parameters.num_items));
            loadVoltTable("ITEM", items);
            items.clearRowData();
        }
        if (this.stop) return;
    } // FOR
    if (items.getRowCount() > 0) {
        String extra = "";
        if (items.getRowCount() < m_parameters.num_items) extra = String.format(" [tuples=%d/%d]", m_parameters.num_items-items.getRowCount(), m_parameters.num_items);
        if (debug.val)
            LOG.debug("Loading replicated ITEM table" + extra);
        loadVoltTable("ITEM", items);
        items.clearRowData();
    }
    items = null;
}
 
Example 20
Project: openjdk-jdk10   File: Type.java   View Source Code Vote up 3 votes
protected boolean addTypes (int typeCodeFilter,
                            HashSet checked,
                            Vector matching) {

    boolean result;

    // Have we already checked this type?

    if (checked.contains(this)) {

        // Yes, so return false.

        result = false;

    } else {

        // Nope, so add it...

        checked.add(this);

        // Do we match the filter?

        if (typeMatches(typeCodeFilter)) {

            // Yep. so add it and set result to true...

            matching.addElement(this);
        }

        // Return true.

        result = true;
    }

    return result;
}