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

The following are Jave code examples for showing how to use contains() of the java.util.ArrayList 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: KrGallery   File: NotificationCenter.java   View Source Code Vote up 6 votes
public void addObserver(Object observer, int id) {
    if (Looper.getMainLooper() != Looper.myLooper()){
            throw new RuntimeException("addObserver allowed only from MAIN thread");
    }

    if (broadcasting != 0) {
        ArrayList<Object> arrayList = addAfterBroadcast.get(id);
        if (arrayList == null) {
            arrayList = new ArrayList<>();
            addAfterBroadcast.put(id, arrayList);
        }
        arrayList.add(observer);
        return;
    }
    ArrayList<Object> objects = observers.get(id);
    if (objects == null) {
        observers.put(id, (objects = new ArrayList<>()));
    }
    if (objects.contains(observer)) {
        return;
    }
    objects.add(observer);
}
 
Example 2
Project: EmoticonGIFKeyboard   File: EmoticonDbHelper.java   View Source Code Vote up 6 votes
/**
 * Get all the emoticons that matches has the search tag starting from search query.
 * If the icon for the emoticon is supported by the emoticon provider then, that emoticon will
 * be added to list.
 *
 * @param searchQuery      Search string.
 * @param emoticonProvider {@link EmoticonProvider} or null for system emoticons.
 * @return List of all the supported emoticons for given emoticon icon pack.
 * @see com.kevalpatel2106.emoticongifkeyboard.emoticons.EmoticonProvider#hasEmoticonIcon(String)
 */
@NonNull
ArrayList<Emoticon> searchEmoticons(@NonNull final String searchQuery,
                                    @Nullable EmoticonProvider emoticonProvider) {
    SQLiteDatabase sqLiteDatabase = getReadableDatabase();
    Cursor cursor = sqLiteDatabase.query(EmoticonTagsColumns.TABLE,
            new String[]{EmoticonTagsColumns.UNICODE},      //Unicode.
            EmoticonTagsColumns.TAG + " LIKE ?", new String[]{searchQuery.trim() + "%"}, //Search for the tag
            null, null, null);

    ArrayList<Emoticon> emoticons = new ArrayList<>();
    while (cursor.moveToNext()) {
        String unicode = cursor.getString(cursor.getColumnIndex(EmoticonTagsColumns.UNICODE));

        //Check if there is icon available to display for custom emoticon page.
        if (emoticonProvider == null || emoticonProvider.hasEmoticonIcon(unicode)) {
            Emoticon emoticon = new Emoticon(unicode);
            if (!emoticons.contains(emoticon))  //Prevent duplicates.
                emoticons.add(new Emoticon(unicode));
        }
    }
    cursor.close();
    sqLiteDatabase.close();
    return emoticons;
}
 
Example 3
Project: World-Border   File: CmdHelp.java   View Source Code Vote up 6 votes
@Override
public void execute(ICommandSender sender, EntityPlayerMP player, List<String> params, String worldName)
{
    if (params.isEmpty())
    {
        sendCmdHelp(sender);
        return;
    }

    ArrayList<String> commands = WorldBorder.COMMAND.getCommandNames();
    for (String param : params)
        if (commands.contains(param.toLowerCase()))
        {
            WorldBorder.COMMAND.subCommands.get(param.toLowerCase()).sendCmdHelp(sender);
            return;
        }

    sendErrorAndHelp(sender, "No command recognized.");
}
 
Example 4
Project: Tarski   File: AlloyUtilities.java   View Source Code Vote up 6 votes
/**
 * This method is used to when iMarker has marker type and we want to find it's sources both have
 * marker type or not.
 *
 * @param iMarker
 * @return
 */
public static ArrayList<IMarker> getSumSources(IMarker iMarker) {
  iMarker = MarkUtilities.getLeaderOfMarker(iMarker);

  final Map<IMarker, String> sourcesMap = AlloyUtilities.getRelationsOfSecondSideMarker(iMarker);
  final ArrayList<IMarker> sourcesList = AlloyUtilities.getSourcesOfMarkerAtRelations(iMarker);

  final ArrayList<IMarker> resultList = new ArrayList<>(sourcesList);

  final Set<IMarker> sourceMarkers = sourcesMap.keySet();
  final Iterator<IMarker> iter = sourceMarkers.iterator();
  while (iter.hasNext()) {
    final IMarker iMarkerSet = iter.next();
    if (!sourcesList.contains(iMarkerSet)) {
      resultList.add(iMarkerSet);
    }
  }
  return resultList;
}
 
Example 5
Project: Bigbang   File: SharedIntentHelper.java   View Source Code Vote up 5 votes
public static void saveShareAppIndexs2Sp(List<ResolveInfoWrap> list, Context context) {
    ArrayList<String> string = new ArrayList<>();
    for (ResolveInfoWrap resolveInfoWrap : list) {
        String name =resolveInfoWrap.resolveInfo.loadLabel(context.getPackageManager()).toString();
        if(!string.contains(name))
            string.add(name);
    }
    context.getSharedPreferences(ShareAppManagerActivity.SHARE_APPS, Context.MODE_PRIVATE).edit().
            putString(ConstantUtil.SHARE_APP_INDEX, new Gson().toJson(string)).apply();
}
 
Example 6
Project: Nearby   File: MedicineDetail.java   View Source Code Vote up 5 votes
public void convert(JSONObject temp){


        ArrayList<String> keySet = AdditionalFunc.getKeySet(temp.keys());

        try {

            if(keySet.contains("code")){
                code = (String) temp.get("code");
            }
            if(keySet.contains("ingredient")){
                ingredient = (String) temp.get("ingredient");
            }
            if(keySet.contains("classification")){
                classification = (String) temp.get("classification");
            }
            if(keySet.contains("url")){
                url = (String) temp.get("url");
            }
            if(keySet.contains("usage_capacity")){
                usageCapacity = (String) temp.get("usage_capacity");
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }
 
Example 7
Project: ZooKeeper   File: PrepRequestProcessor.java   View Source Code Vote up 5 votes
private List<ACL> removeDuplicates(List<ACL> acl) {

        ArrayList<ACL> retval = new ArrayList<ACL>();
        Iterator<ACL> it = acl.iterator();
        while (it.hasNext()) {
            ACL a = it.next();
            if (retval.contains(a) == false) {
                retval.add(a);
            }
        }
        return retval;
    }
 
Example 8
Project: Nearby   File: Medicine.java   View Source Code Vote up 5 votes
public void convert(JSONObject temp){


        ArrayList<String> keySet = AdditionalFunc.getKeySet(temp.keys());

        try {

            if(keySet.contains("medicine_id")){
                id = (String) temp.get("medicine_id");
            }
            if(keySet.contains("medicine_type")){
                type = (String) temp.get("medicine_type");
            }
            if(keySet.contains("medicine_code")){
                code = (String) temp.get("medicine_code");
            }
            if(keySet.contains("medicine_name")){
                name = (String) temp.get("medicine_name");
            }
            if(keySet.contains("medicine_company")){
                company = (String) temp.get("medicine_company");
            }
            if(keySet.contains("medicine_standard")){
                standard = (String) temp.get("medicine_standard");
            }
            if(keySet.contains("medicine_unit")){
                unit = (String) temp.get("medicine_unit");
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }
 
Example 9
Project: LD38   File: Shader.java   View Source Code Vote up 5 votes
public static void destroyAll(){
	ArrayList<Shader> checks = new ArrayList<Shader>();
	//clear the objects
	for(Shader shader : shaders.values()){
		if(!checks.contains(shader)){
			shader.destroy();
			checks.add(shader);
		}
	}
	
	//clear out all of the objects
	checks.clear();
	shaders.clear();
}
 
Example 10
Project: logistimo-web-service   File: TagUtil.java   View Source Code Vote up 5 votes
public static String getCleanTags(String commaSepTags, boolean sort) {
  if (commaSepTags == null || commaSepTags.isEmpty()) {
    return commaSepTags;
  }
  String[] tagsA = commaSepTags.split(",");
  if (tagsA == null || tagsA.length == 0) {
    return commaSepTags.trim();
  }
  if (sort) {
    Arrays.sort(tagsA, new TagUtil.TagComparator());
  }
  String tTags = "";
  ArrayList<String> tagsL = new ArrayList<String>();
  ArrayList<String> dedupL = new ArrayList<String>();
  for (int i = 0; i < tagsA.length; i++) {
    if (!dedupL.contains(tagsA[i].toLowerCase())) {
      tagsL.add(tagsA[i]);
      dedupL.add(tagsA[i].toLowerCase());
      if (i != 0) {
        tTags += ",";
      }
      tTags += tagsA[i].trim();
    }
  }

  return tTags;
}
 
Example 11
Project: DIA-Umpire-Maven   File: PepIonID.java   View Source Code Vote up 5 votes
public float GetPepAbundanceByTopCorrFragAcrossSample(ArrayList<String> PepFrag) {
    float totalabundance = 0f;
    int count = 0;
    if (PepFrag != null && FragmentPeaks != null) {
        for (FragmentPeak frag : FragmentPeaks) {
            if (PepFrag.contains(frag.GetFragKey())) {
                totalabundance += frag.intensity;
                count++;
            }
        }
    }
    return totalabundance;
}
 
Example 12
Project: Achtbaan   File: EntityClick_Listener.java   View Source Code Vote up 5 votes
@EventHandler
public void ArmorStandGreef(PlayerArmorStandManipulateEvent e){
	if(e.getRightClicked() instanceof ArmorStand){
		ArmorStand clickedA = (ArmorStand) e.getRightClicked();
		if(clickedA.getPassenger() == null){
			ArrayList<ArmorStand> all_main_seats = new ArrayList<ArmorStand>();
			for(attractie att : Main.r.Attracties.values()){
				all_main_seats.addAll(att.getMainSeats());
			}
			if(all_main_seats.contains(clickedA)){
				e.setCancelled(true);
			}
		}
	}
}
 
Example 13
Project: m6ASNP   File: Tree.java   View Source Code Vote up 5 votes
private void SplitDiscreteData(ArrayList<double[]> parentDataList, ArrayList<double[]> leftDataList, ArrayList<double[]> rightDataList, ArrayList<Double> splitValueList, int attrIndex)
{
    leftDataList.clear();
    rightDataList.clear();
    double checkAttribute = 0;
    for(int i=0; i<parentDataList.size(); i++)
    {
        checkAttribute = parentDataList.get(i)[attrIndex];
        if(splitValueList.contains(checkAttribute))
            leftDataList.add(parentDataList.get(i));
        else
            rightDataList.add(parentDataList.get(i));
    }
}
 
Example 14
Project: OpenHub   File: IssueTimelinePresenter.java   View Source Code Vote up 5 votes
public ArrayList<String> getIssueUsersExceptMe(){
    if(timeline == null) return null;
    ArrayList<String> users = new ArrayList<String>();
    for(IssueEvent event : timeline){
        if(!AppData.INSTANCE.getLoggedUser().getLogin().equals(event.getUser().getLogin())
                && !users.contains(event.getUser().getLogin())){
            users.add(event.getUser().getLogin());
        }
    }
    return users;
}
 
Example 15
Project: MaxSim   File: Node.java   View Source Code Vote up 5 votes
public List<Node<N, E>> getSuccessors() {
    ArrayList<Node<N, E>> succ = new ArrayList<>();
    for (Edge<N, E> e : getOutEdges()) {
        Node<N, E> n = e.getDest();
        if (!succ.contains(n)) {
            succ.add(n);
        }
    }
    return succ;
}
 
Example 16
Project: Saiy-PS   File: SongRecognitionChooser.java   View Source Code Vote up 5 votes
private static ArrayList<SongRecognitionChooser> removeDuplicates(
        @NonNull final ArrayList<SongRecognitionChooser> chooserList) {
    if (DEBUG) {
        MyLog.i(CLS_NAME, "prepareChooser");
    }

    final ArrayList<String> packageList = new ArrayList<>();
    final Iterator<SongRecognitionChooser> itr = chooserList.iterator();

    String packageName;
    SongRecognitionChooser src;
    while (itr.hasNext()) {
        src = itr.next();
        packageName = src.getPackageName();

        if (packageList.contains(packageName)) {
            if (DEBUG) {
                MyLog.v(CLS_NAME, "src removed: " + packageName);
            }

            itr.remove();
        } else {
            packageList.add(packageName);
        }
    }

    return chooserList;
}
 
Example 17
Project: ID3-Decision-Tree-Classifier-in-Java   File: RandomForest.java   View Source Code Vote up 4 votes
public RandomForest(int noOfTrees, double fractionOfAttributesToTake, double fractionOfInstancesToTake, ArrayList<String[]> data, ArrayList<String[]> testData, int noOfClass1, int noOfClass2, 
		String class1, String class2, HashMap<Integer, ArrayList<String>> discreteValues){
	if(fractionOfAttributesToTake>1 || fractionOfAttributesToTake<0 || fractionOfInstancesToTake>1 || fractionOfInstancesToTake<0){
		System.out.println("Random Forest input invalid");
		return;
	}
		
	this.noOfTrees = noOfTrees;
	this.data = data;
	this.class1 = class1;
	this.class2 = class2;
	this.testData = testData;
	this.discreteValues = discreteValues;
	
	int noOfAttributes = data.get(0).length-1, noOfTrainingInstances = data.size();
	int noOfRandomInstances = (int)(noOfTrainingInstances*fractionOfInstancesToTake);
	int noOfRandomAttributes = (int)(noOfAttributes*fractionOfAttributesToTake);
	
	String[][] dataInArray = new String[noOfTrainingInstances][];//to access randomly in constant time
	int x = 0;
	for(String[] s : data){
		dataInArray[x++] = s;
	}
	
	trainingTime = System.currentTimeMillis();
	
	Random rand = new Random();
	tree = new ID3[noOfTrees];
	for(int i = 0; i < noOfTrees; i++){
		ArrayList<Integer> remAttr = new ArrayList<>();
		for(int j = 0; j < noOfRandomAttributes; j++){
			int r = rand.nextInt(noOfAttributes);
			if(remAttr.contains(r))	j--;
			else remAttr.add(r);
		}
		ArrayList<String[]> randData = new ArrayList<>();
		for(int j = 0; j < noOfRandomInstances; j++){
			randData.add(dataInArray[rand.nextInt(noOfTrainingInstances)]);
		}
		tree[i] = new ID3(randData, testData, noOfClass1, noOfClass2, class1, class2, discreteValues, remAttr);
	}
	
	trainingTime = (System.currentTimeMillis() - trainingTime)/1000.0;
	
	analyse();
}
 
Example 18
Project: incubator-netbeans   File: OptionsChooserPanel.java   View Source Code Vote up 4 votes
/** Returns tree model based on current state of OptionsExportModel. Sets treeModel field. */
private TreeModel createOptionsTreeModel() {
    LOGGER.fine("getOptionsTreeModel - " + getOptionsExportModel());  //NOI18N
    String allLabel = NbBundle.getMessage(OptionsChooserPanel.class, "OptionsChooserPanel.outline.all");
    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(allLabel);
    ArrayList<String> enabledItems = new ArrayList<String>();
    double buildNumberDuringExport = 0;
    double currentBuildNumber;
    String nbBuildNumber = System.getProperty("netbeans.buildnumber"); // NOI18N
    try {
        currentBuildNumber = Double.parseDouble(getOptionsExportModel().parseBuildNumber(nbBuildNumber));
    } catch (NumberFormatException nfe) {
        LOGGER.log(Level.INFO, "Could not parse netbeans.buildnumber: {0}", nbBuildNumber);  //NOI18N
        currentBuildNumber = 201403101706.0;  // default to build date of 8.0 version
    }
    if (panelType == PanelType.IMPORT) {
        // If the returned value is null, it means that there is no enabledItems.info in the importing zip file
        // indicating it was created from a version prior to 7.4
        enabledItems = getOptionsExportModel().getEnabledItemsDuringExport(new File(txtFile.getText()));
        // If the returned value is -1, it means that there is no build.info in the importing zip file or userdir
        // or that there was an exception while trying to parse the build number
        buildNumberDuringExport = getOptionsExportModel().getBuildNumberDuringExport(new File(txtFile.getText()));
    }
    for (OptionsExportModel.Category category : getOptionsExportModel().getCategories()) {
        LOGGER.fine("category=" + category);  //NOI18N
        DefaultMutableTreeNode categoryNode = new DefaultMutableTreeNode(category);
        List<OptionsExportModel.Item> items = category.getItems();
        for (OptionsExportModel.Item item : items) {
            LOGGER.fine("    item=" + item);  //NOI18N
            if (panelType == PanelType.EXPORT || item.isApplicable()) {
                // do not show not applicable items for import
                if (panelType == PanelType.IMPORT) {
                    // avoid false possitives, check the items that were explicitly selected by the user during export
                    if (enabledItems == null || enabledItems.contains(category.getDisplayName().concat(item.getDisplayName()))
                            // special treatment as Projects category was introduced after 7.4, so when trying to import options,
                            // exported from 7.4, into 8.0 or later there would be no Project category in enabledItems.info file.
                            // There must be GeneralAll Other Unspecified present in the extracted enabledItems.info file though.
                            || (category.getDisplayName().equals("Projects") && enabledItems.contains("GeneralAll Other Unspecified")  // NOI18N
                                && buildNumberDuringExport >= 201310111528.0 // build date of 7.4 version
                                && currentBuildNumber >= 201403101706.0)) { // build date of 8.0 version
                        categoryNode.add(new DefaultMutableTreeNode(item));
                    }
                } else {
                    categoryNode.add(new DefaultMutableTreeNode(item));
                }
            }
        }
        if (categoryNode.getChildCount() != 0) {
            // do not show category node if it has no children
            rootNode.add(categoryNode);
            updateCategoryNode(categoryNode);
        }
    }
    if (rootNode.getChildCount() == 0) {
        rootNode = null;
    }
    treeModel = new DefaultTreeModel(rootNode);
    return treeModel;
}
 
Example 19
Project: OpenJSharp   File: Sort.java   View Source Code Vote up 4 votes
/**
 * Create a new auxillary class extending NodeSortRecord.
 */
private static String compileSortRecord(Vector sortObjects,
                                        ClassGenerator classGen,
                                        MethodGenerator methodGen) {
    final XSLTC  xsltc = ((Sort)sortObjects.firstElement()).getXSLTC();
    final String className = xsltc.getHelperClassName();

    // This generates a new class for handling this specific sort
    final NodeSortRecordGenerator sortRecord =
        new NodeSortRecordGenerator(className,
                                    NODE_SORT_RECORD,
                                    "sort$0.java",
                                    ACC_PUBLIC | ACC_SUPER | ACC_FINAL,
                                    new String[] {},
                                    classGen.getStylesheet());

    final ConstantPoolGen cpg = sortRecord.getConstantPool();

    // Add a new instance variable for each var in closure
    final int nsorts = sortObjects.size();
    final ArrayList dups = new ArrayList();

    for (int j = 0; j < nsorts; j++) {
        final Sort sort = (Sort) sortObjects.get(j);

        // Set the name of the inner class in this sort object
        sort.setInnerClassName(className);

        final int length = (sort._closureVars == null) ? 0 :
            sort._closureVars.size();
        for (int i = 0; i < length; i++) {
            final VariableRefBase varRef = (VariableRefBase) sort._closureVars.get(i);

            // Discard duplicate variable references
            if (dups.contains(varRef)) continue;

            final VariableBase var = varRef.getVariable();
            sortRecord.addField(new Field(ACC_PUBLIC,
                                cpg.addUtf8(var.getEscapedName()),
                                cpg.addUtf8(var.getType().toSignature()),
                                null, cpg.getConstantPool()));
            dups.add(varRef);
        }
    }

    MethodGenerator init = compileInit(sortObjects, sortRecord,
                                     cpg, className);
    MethodGenerator extract = compileExtract(sortObjects, sortRecord,
                                    cpg, className);
    sortRecord.addMethod(init);
    sortRecord.addMethod(extract);

    xsltc.dumpClass(sortRecord.getJavaClass());
    return className;
}
 
Example 20
Project: alevin-svn2   File: FixedMLSDemandGenerator.java   View Source Code Vote up 4 votes
@Override
public Integer generate(ArrayList<Object> parameters) {
	NetworkStack ns = (NetworkStack)parameters.get(0);
	Integer sLevels = ConversionHelper.paramObjectToInteger(parameters.get(1));
	Integer sCats = ConversionHelper.paramObjectToInteger(parameters.get(2));
	Long seed = ConversionHelper.paramObjectToLong(parameters.get(3));
	
	Random random = new Random();
	random.setSeed(seed);
	
	MLSLattice lattice = RandomMLSResourceGenerator.createLattice(sLevels, sCats);
	
	
	int maxLevel = lattice.getNumberOfLevels() - 1;
	ArrayList<String> cats = lattice.getCategories();
	
	for(int u = 1; u < ns.size(); u++) {
	
		VirtualNetwork vNetwork = (VirtualNetwork)ns.getLayer(u);
		
		for (VirtualNode n : vNetwork.getVertices()) {
			//Create Random resource
			int resDem = (int)((maxLevel + 1) * random.nextDouble());
			int resProv = (int)((maxLevel + 1) * random.nextDouble());
		
			//we need at least one Category
			int countCat;
			do {
				countCat = (int)((cats.size()+1) * random.nextDouble());
			} while (countCat < 1);
			ArrayList<String> chosenCats = new ArrayList<String>();
			for (int c = 0; c < countCat; c++) {
				String cat;
				do {
					cat = cats.get((int)(cats.size() * random.nextDouble()));
				} while (chosenCats.contains(cat));
				chosenCats.add(cat);
			}

				MLSDemand res = new MLSDemand(n, resDem, resProv, chosenCats);
			n.add(res);
		}
	}
	return 0;
}