Java Code Examples for java.util.ArrayList#removeAll()

The following examples show how to use java.util.ArrayList#removeAll() . 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: Utils.java    From loco-answers with GNU General Public License v3.0 6 votes vote down vote up
public static String getSimplifiedString(String text, @Nullable String optionalRemoveWord) {
    String[] split = text.split(" ");
    ArrayList<String> list = new ArrayList<>(Arrays.asList(split));
    list.removeAll(Data.removeWords);

    if (optionalRemoveWord != null) {
        String x[] = optionalRemoveWord.split(" ");
        ArrayList<String> x2 = new ArrayList<>(Arrays.asList(x));
        list.removeAll(x2);
    }

    StringBuilder stringBuilder = new StringBuilder();
    for (String s : list) {
        stringBuilder.append(s).append(" ");
    }
    return stringBuilder.toString();
}
 
Example 2
Source File: ProjectLibraryActions.java    From Logisim with GNU General Public License v3.0 6 votes vote down vote up
public static void doLoadBuiltinLibrary(Project proj) {
	LogisimFile file = proj.getLogisimFile();
	List<Library> baseBuilt = file.getLoader().getBuiltin().getLibraries();
	ArrayList<Library> builtins = new ArrayList<Library>(baseBuilt);
	builtins.removeAll(file.getLibraries());
	if (builtins.isEmpty()) {
		JOptionPane.showMessageDialog(proj.getFrame(), Strings.get("loadBuiltinNoneError"),
				Strings.get("loadBuiltinErrorTitle"), JOptionPane.INFORMATION_MESSAGE);
		return;
	}
	LibraryJList list = new LibraryJList(builtins);
	JScrollPane listPane = new JScrollPane(list);
	int action = JOptionPane.showConfirmDialog(proj.getFrame(), listPane, Strings.get("loadBuiltinDialogTitle"),
			JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE);
	if (action == JOptionPane.OK_OPTION) {
		Library[] libs = list.getSelectedLibraries();
		if (libs != null)
			proj.doAction(LogisimFileActions.loadLibraries(libs));
	}
}
 
Example 3
Source File: PipelineExecutor.java    From hop with Apache License 2.0 6 votes vote down vote up
protected List<String> getLastIncomingFieldValues() {
  PipelineExecutorData pipelineExecutorData = getData();
  List<String> lastIncomingFieldValues = new ArrayList<>();
  if ( pipelineExecutorData == null || pipelineExecutorData.groupBuffer.isEmpty() ) {
    return null;
  }

  int lastIncomingFieldIndex = pipelineExecutorData.groupBuffer.size() - 1;
  ArrayList lastGroupBufferData = new ArrayList( Arrays.asList( pipelineExecutorData.groupBuffer.get( lastIncomingFieldIndex ).getData() ) );
  lastGroupBufferData.removeAll( Collections.singleton( null ) );

  for ( int i = 0; i < lastGroupBufferData.size(); i++ ) {
    lastIncomingFieldValues.add( lastGroupBufferData.get( i ).toString() );
  }
  return lastIncomingFieldValues;
}
 
Example 4
Source File: BackupActivity.java    From andOTP with MIT License 6 votes vote down vote up
private void restoreEntries(String text) {
    ArrayList<Entry> entries = DatabaseHelper.stringToEntries(text);

    if (entries.size() > 0) {
        if (! replace.isChecked()) {
            ArrayList<Entry> currentEntries = DatabaseHelper.loadDatabase(this, encryptionKey);

            entries.removeAll(currentEntries);
            entries.addAll(currentEntries);
        }

        if (DatabaseHelper.saveDatabase(this, entries, encryptionKey)) {
            reload = true;
            Toast.makeText(this, R.string.backup_toast_import_success, Toast.LENGTH_LONG).show();
            finishWithResult();
        } else {
            Toast.makeText(this, R.string.backup_toast_import_save_failed, Toast.LENGTH_LONG).show();
        }
    } else {
        Toast.makeText(this, R.string.backup_toast_import_no_entries, Toast.LENGTH_LONG).show();
    }
}
 
Example 5
Source File: RefreshProcessManager.java    From opencards with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public void setupSchedule(Collection<CardFile> curFiles) {
    scheduler.clear();

    // finally reorder files based on urgentness
    List<CardFile> presortFiles = new ArrayList<CardFile>(curFiles);
    presortFiles.sort(new Comparator<CardFile>() {
        public int compare(CardFile o1, CardFile o2) {
            return (int) (ScheduleUtils.getUrgency(o1.getFlashCards().getLTMItems()) -
                    ScheduleUtils.getUrgency(o2.getFlashCards().getLTMItems()));
        }
    });

    for (CardFile presortFile : presortFiles) {
        ArrayList<Item> fileItems = new ArrayList(presortFile.getFlashCards().getLTMItems());

        // remove new items (because this a refreshing scheduler)
        fileItems.removeAll(ScheduleUtils.getNewItems(fileItems));

        numScheduled += fileItems.size();

        scheduler.put(presortFile, fileItems);
    }

    procIt = scheduler.keySet().iterator();
}
 
Example 6
Source File: RSCPacketFilter.java    From Game with GNU General Public License v3.0 6 votes vote down vote up
private final int getPacketsPerSecond(final Channel connection) {
	final long now = System.currentTimeMillis();
	int pps = 0;

	synchronized (packets) {
		if(packets.containsKey(connection)) {
			ArrayList<Long> packetTimes = packets.get(connection);
			ArrayList<Long> packetsToRemove = new ArrayList<Long>();

			for (Long packetCreationTime : packetTimes) {
				if (now - packetCreationTime < 1000) {
					pps++;
				} else {
					packetsToRemove.add(packetCreationTime);
				}
			}
			packetTimes.removeAll(packetsToRemove);
		}
	}
	return pps;
}
 
Example 7
Source File: CycleDetector.java    From Digital with GNU General Public License v3.0 6 votes vote down vote up
private static void checkGraphForCycles(Collection<Node> nodes) throws CycleException {
    ArrayList<Node> remaining = new ArrayList<>(nodes);

    int layer = 1;
    while (!remaining.isEmpty()) {
        layer++;
        ArrayList<Node> ableToPlace = new ArrayList<>();
        for (Node node : remaining) {
            boolean nodeOk = true;
            for (Node p : node.parents)
                if (p.layer == 0) {
                    nodeOk = false;
                    break;
                }
            if (nodeOk) {
                ableToPlace.add(node);
                node.layer = layer;
            }
        }

        if (ableToPlace.isEmpty())
            throw new CycleException();

        remaining.removeAll(ableToPlace);
    }
}
 
Example 8
Source File: MiscUtils.java    From BedWars with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static Player findTarget(Game game, Player player, double maxDist) {
    Player playerTarget = null;
    RunningTeam team = game.getTeamOfPlayer(player);

    ArrayList<Player> foundTargets = new ArrayList<>(game.getConnectedPlayers());
    foundTargets.removeAll(team.getConnectedPlayers());


    for (Player p : foundTargets) {
        GamePlayer gamePlayer = Main.getPlayerGameProfile(p);
        if (player.getWorld() != p.getWorld()) {
            continue;
        }

        if (gamePlayer.isSpectator) {
            continue;
        }

        double realDistance = player.getLocation().distance(p.getLocation());
        if (realDistance < maxDist) {
            playerTarget = p;
            maxDist = realDistance;
        }
    }
    return playerTarget;
}
 
Example 9
Source File: Playlist.java    From NoteBlockAPI with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Removes songs from playlist
 * @param songs
 * @throws IllegalArgumentException when you try to remove all {@link Song} from {@link Playlist}
 */
public void remove(Song ...songs){
	ArrayList<Song> songsTemp = new ArrayList<>();
	songsTemp.addAll(this.songs);
	songsTemp.removeAll(Arrays.asList(songs));
	if (songsTemp.size() > 0){
		this.songs = songsTemp;
	} else {
		throw new IllegalArgumentException("Cannot remove all songs from playlist");
	}
}
 
Example 10
Source File: Armor.java    From shattered-pixel-dungeon-gdx with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Glyph randomCurse( Class<? extends Glyph> ... toIgnore ){
	ArrayList<Class<?>> glyphs = new ArrayList<>(Arrays.asList(curses));
	glyphs.removeAll(Arrays.asList(toIgnore));
	if (glyphs.isEmpty()) {
		return random();
	} else {
		return (Glyph) Reflection.newInstance(Random.element(glyphs));
	}
}
 
Example 11
Source File: GTPlanarizer.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * TODO: need to optimize
 * @param faces
 * @return
 */
private Collection<ArrayList<Face>> computeFaceLists(ArrayList<Face> faces) {
    Collection<ArrayList<Face>> faceLists = new ArrayList<ArrayList<Face>>();
    faces = new ArrayList<Face>(faces);

    while (!faces.isEmpty()) {
        ArrayList<Face> faceList = new ArrayList<Face>();
        faceLists.add(faceList);
        Face firstFace = faces.remove(0);
        faceList.add(firstFace);

        for (int i = 0; i < faceList.size(); i++) {
            Collection<Face> connectedFaces = new ArrayList<Face>();
            Face iface = faceList.get(i);

            for (int j = 0; j < faces.size(); j++) {
                Face jface = faces.get(j);

                if (iface.connects(jface)) {
                    connectedFaces.add(jface);
                }
            }

            faces.removeAll(connectedFaces);
            faceList.addAll(connectedFaces);
        }
    }

    return faceLists;
}
 
Example 12
Source File: Weapon.java    From shattered-pixel-dungeon with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static Enchantment randomRare( Class<? extends Enchantment> ... toIgnore ) {
	ArrayList<Class<?>> enchants = new ArrayList<>(Arrays.asList(rare));
	enchants.removeAll(Arrays.asList(toIgnore));
	if (enchants.isEmpty()) {
		return random();
	} else {
		return (Enchantment) Reflection.newInstance(Random.element(enchants));
	}
}
 
Example 13
Source File: SimpleStringCleaning.java    From Java-for-Data-Science with MIT License 5 votes vote down vote up
public static void removeStopWords(String text){
	//discuss stop words file - how to choose stop words? use whole alphabet as way to handle I'M --> I M

	//****************** SIMPLE EXAMPLE *******************************************************************************************

	try {
		//read in list of stop words
		Scanner readStop = new Scanner(new File("C://Jenn Personal//Packt Data Science//Chapter 3 Data Cleaning//stopwords.txt"));
		//create an ArrayList to hold dirty text - call simpleCleanToArray to perform basic cleaning and put in array first
		ArrayList<String> words = new ArrayList<String>(Arrays.asList(simpleCleanToArray(text)));
		//loop through stop words file and check array for each word
		out.println("Original clean text: " + words.toString());
		ArrayList<String> foundWords = new ArrayList();
		while(readStop.hasNextLine()){
			String stopWord = readStop.nextLine().toLowerCase();
			if(words.contains(stopWord)){
				foundWords.add(stopWord);
			}
		}
		words.removeAll(foundWords);
		out.println("Text without stop words: " + words.toString());
	} catch (FileNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

}
 
Example 14
Source File: CaseExpressionTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * Execute the received caseExpression on the received Statement
 * and check the results against the receieved expected array.
 */
private void testCaseExpressionQuery(Statement st,
    String [][] expRS, String caseExprBegin, String caseExprEnd)
    throws SQLException
{
    ResultSet rs;
    int colType;
    int row;

    for (colType = 0;
        colType < SQLUtilities.SQLTypes.length;
        colType++)
    {
        rs = st.executeQuery(
            caseExprBegin +
            SQLUtilities.allDataTypesColumnNames[colType] +
            caseExprEnd);

        // GemStone changes BEGIN   : use unordered result set comparison
        ArrayList expected = new ArrayList(Arrays.asList(expRS[colType]));
        ArrayList actual = new ArrayList();
        //row = 0;
        while (rs.next()) {
          actual.add(rs.getString(1));
            //String val = rs.getString(1);
            //assertEquals(expRS[colType][row], val);
            //row++;
        }
        rs.close();
        Assert.assertEquals("Unexpected row count",
            expected.size(), actual.size());
        Assert.assertTrue("Missing rows in ResultSet",
            actual.containsAll(expected));
        actual.removeAll(expected);
        Assert.assertTrue("Extra rows in ResultSet", actual.isEmpty());

        // GemStone changes END
    }
}
 
Example 15
Source File: NegatingPrimitive.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
@Override
public <R> Collection<? extends R> getCollection(PlayerCharacter pc, Converter<T, R> c)
{
	Collection<? extends R> result = all.getCollection(pc, c);
	ArrayList<R> list = new ArrayList<>(result);
	list.removeAll(primitive.getCollection(pc, c));
	return list;
}
 
Example 16
Source File: FragmentTransitionCompat21.java    From adt-leanback-support with Apache License 2.0 5 votes vote down vote up
public static Object captureExitingViews(Object exitTransition, View root,
        ArrayList<View> viewList, Map<String, View> namedViews) {
    if (exitTransition != null) {
        captureTransitioningViews(viewList, root);
        if (namedViews != null) {
            viewList.removeAll(namedViews.values());
        }
        if (viewList.isEmpty()) {
            exitTransition = null;
        } else {
            addTargets((Transition) exitTransition, viewList);
        }
    }
    return exitTransition;
}
 
Example 17
Source File: Utils.java    From typescript-generator with MIT License 4 votes vote down vote up
public static <T> List<T> removeAll(List<T> list, List<T> toBeRemoved) {
    final ArrayList<T> result = new ArrayList<>(list);
    result.removeAll(toBeRemoved);
    return result;
}
 
Example 18
Source File: SelfAwareVerbose.java    From Saiy-PS with GNU Affero General Public License v3.0 4 votes vote down vote up
/**
 * Iterate through the recognition results and their associated confidence scores.
 *
 * @param bundle of recognition data
 */
public static void logSpeechResults(final Bundle bundle) {
    MyLog.i(CLS_NAME, "logSpeechResults");

    examineBundle(bundle);

    final ArrayList<String> heardVoice = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
    final ArrayList<String> unstable = bundle.getStringArrayList(RecognitionNative.UNSTABLE_RESULTS);
    final float[] confidence = bundle.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES);

    if (heardVoice != null) {
        MyLog.d(CLS_NAME, "heardVoice: " + heardVoice.size());
    }
    if (unstable != null) {
        MyLog.d(CLS_NAME, "unstable: " + unstable.size());
    }
    if (confidence != null) {
        MyLog.d(CLS_NAME, "confidence: " + confidence.length);
    }

    /* handles empty string bug */
    if (UtilsList.notNaked(heardVoice)) {
        heardVoice.removeAll(Collections.singleton(""));
    }

    /* handles empty string bug */
    if (UtilsList.notNaked(unstable)) {
        unstable.removeAll(Collections.singleton(""));
    }

    if (UtilsList.notNaked(confidence) && UtilsList.notNaked(heardVoice) && confidence.length == heardVoice.size()) {
        for (int i = 0; i < heardVoice.size(); i++) {
            MyLog.i(CLS_NAME, "Results: " + heardVoice.get(i) + " ~ " + confidence[i]);
        }
    } else if (UtilsList.notNaked(heardVoice)) {
        for (int i = 0; i < heardVoice.size(); i++) {
            MyLog.i(CLS_NAME, "Results: " + heardVoice.get(i));
        }
    } else if (UtilsList.notNaked(unstable)) {
        for (int i = 0; i < unstable.size(); i++) {
            MyLog.i(CLS_NAME, "Unstable: " + unstable.get(i));
        }
    } else {
        MyLog.w(CLS_NAME, "Results: values error");
    }
}
 
Example 19
Source File: Behavior.java    From cst with GNU Lesser General Public License v3.0 4 votes vote down vote up
/**
 * @return the amount of activation that is spread forward from other modules in the direction of this module
 * 
 *         Note: this approach is slightly different from the one proposed at the article by [Maes 1989] since here we try to avoid meddling with another codelet's states.
 */
public double spreadFw()
{
	// In this case x= other modules, y= this module
	double activation = 0;
	// synchronized(this.predecessors){
	if (!this.getPredecessors().isEmpty())
	{
		Enumeration e = this.getPredecessors().keys();
		// iterate through Hashtable keys Enumeration
		while (e.hasMoreElements())
		{
			Behavior module = (Behavior) e.nextElement();
			if (impendingAccess(module))
			{
				try
				{
					double amount = 0;
					if (module.isExecutable())
					{// An executable competence module x spreads activation forward.
						ArrayList<Memory> intersection = new ArrayList<Memory>();

						ArrayList<Memory> preconPlusSoftPrecon=new ArrayList<Memory>();

						preconPlusSoftPrecon.addAll(this.getListOfPreconditions());
						preconPlusSoftPrecon.addAll(this.getSoftPreconList());


						intersection.addAll(getIntersectionSet(module.getDeleteList(), preconPlusSoftPrecon));
						intersection.removeAll(worldState);
						for (Memory item : intersection)
						{
							amount = amount + ((1.0 / this.competencesWithPropInPrecon(item)) * (1.0 / (double) preconPlusSoftPrecon.size()));
						}
						amount = amount * module.getActivation() * (globalVariables.getPhi() / globalVariables.getGamma());
						if (showActivationSpread)
						{
							System.out.println(this.getName() + " receives " + amount + " forwarded energy from " + module.getName() + " [which has A= " + module.getActivation() + " ]");
						}

					}
					// ------------------------------------------------
					activation = activation + amount;
				} finally
				{
					lock.unlock();
					module.lock.unlock();
				}
			}
		}
	}
	// }//end synch
	return activation;
}
 
Example 20
Source File: NodeModulesDiscoveryHelper.java    From n4js with Eclipse Public License 1.0 4 votes vote down vote up
/** @return {@link #localNodeModulesFolder} and {@link #workspaceNodeModulesFolder} iff not null */
public List<File> getNodeModulesFolders() {
	ArrayList<File> nmfList = Lists.newArrayList(this.workspaceNodeModulesFolder, this.localNodeModulesFolder);
	nmfList.removeAll(Collections.singleton(null));
	return Collections.unmodifiableList(nmfList);
}