Example usage for java.util Iterator remove

List of usage examples for java.util Iterator remove

Introduction

In this page you can find the example usage for java.util Iterator remove.

Prototype

default void remove() 

Source Link

Document

Removes from the underlying collection the last element returned by this iterator (optional operation).

Usage

From source file:com.comphenix.protocol.events.PacketMetadata.java

public static <T> Optional<T> remove(Object packet, String key) {
    Validate.notNull(key, "Null keys are not permitted!");

    if (META_CACHE == null) {
        return Optional.empty();
    }//w  ww . j a  v  a  2  s.co  m

    List<MetaObject> packetMeta = META_CACHE.getIfPresent(packet);
    if (packetMeta == null) {
        return Optional.empty();
    }

    Optional<T> value = Optional.empty();
    Iterator<MetaObject> iter = packetMeta.iterator();
    while (iter.hasNext()) {
        MetaObject meta = iter.next();
        if (meta.key.equals(key)) {
            value = Optional.of((T) meta.value);
            iter.remove();
        }
    }

    return value;
}

From source file:fr.lirmm.graphik.util.MathUtils.java

/**
 * Comput the cartesian product of the specified set with itself.
 * input: { A, B, C }/*from w w  w .  jav  a  2 s. c  om*/
 * output : { (A,A), (A,B), (B,B) } 
 * @param set
 * @return
 */
public static <T> Iterable<Pair<T, T>> selfCartesianProduct(Iterable<T> set) {
    Collection<Pair<T, T>> pairs = new LinkedList<Pair<T, T>>();

    Iterator<T> it = set.iterator();
    while (it.hasNext()) {
        T a = it.next();
        for (T b : set) {
            pairs.add(new ImmutablePair<T, T>(a, b));
        }

        if (it.hasNext()) { // FIXfor singleton implementation
            it.remove();
        }
    }
    return pairs;
}

From source file:com.bruce.intellijplugin.generatesetter.utils.PsiToolUtils.java

public static void addImportToFile(PsiDocumentManager psiDocumentManager, PsiJavaFile containingFile,
        Document document, Set<String> newImportList) {
    if (newImportList.size() > 0) {
        Iterator<String> iterator = newImportList.iterator();
        while (iterator.hasNext()) {
            String u = iterator.next();
            if (u.startsWith("java.lang")) {
                iterator.remove();
            }/*from ww w  . j av  a 2s.  c o m*/
        }
    }

    if (newImportList.size() > 0) {
        PsiJavaFile javaFile = containingFile;
        PsiImportStatement[] importStatements = javaFile.getImportList().getImportStatements();
        Set<String> containedSet = new HashSet<>();
        for (PsiImportStatement s : importStatements) {
            containedSet.add(s.getQualifiedName());
        }
        StringBuilder newImportText = new StringBuilder();
        for (String newImport : newImportList) {
            if (!containedSet.contains(newImport)) {
                newImportText.append("\nimport " + newImport + ";");
            }
        }
        PsiPackageStatement packageStatement = javaFile.getPackageStatement();
        int start = 0;
        if (packageStatement != null) {
            start = packageStatement.getTextLength() + packageStatement.getTextOffset();
        }
        String insertText = newImportText.toString();
        if (StringUtils.isNotBlank(insertText)) {
            document.insertString(start, insertText);
            PsiDocumentUtils.commitAndSaveDocument(psiDocumentManager, document);
        }
    }
}

From source file:Main.java

/**
 * Return a new Set with elements that are in the first and second passed collection.
 * If one set is null, an empty Set will be returned.
 * @param  <T>    Type of set/*from   ww  w  . j a va  2 s.  c om*/
 * @param  first  First set
 * @param  second Second set
 *
 * @return a new set (depending on input type) with elements in first and second
 */
static <T> Set<T> intersection(Set<T> first, Set<T> second) {
    Set<T> result = new HashSet<T>();
    if ((first != null) && (second != null)) {
        result.addAll(first);
        //            result.retainAll(second);
        Iterator<T> iter = result.iterator();
        boolean found;
        while (iter.hasNext()) {
            T item = iter.next();
            found = false;
            for (T s : second) {
                if (s.equals(item))
                    found = true;
            }
            if (!found)
                iter.remove();
        }
    }

    return result;
}

From source file:Main.java

public static List<Integer> checkIdentical(List<Integer> list1, List<Integer> list2) {
    List<Integer> resultList = new ArrayList<Integer>();

    Iterator<Integer> iterator1 = list1.iterator();
    while (iterator1.hasNext()) {
        Integer next1 = iterator1.next();
        Iterator<Integer> iterator2 = list2.iterator();
        while (iterator2.hasNext()) {
            Integer next2 = iterator2.next();
            if (next1.intValue() == next2.intValue()) {
                iterator1.remove();
                iterator2.remove();//from  ww w.j a  v  a  2 s  . c  o m
                resultList.add(next1.intValue());
                break;
            }
        }
    }

    return resultList;
}

From source file:net.sourceforge.fenixedu.applicationTier.Servico.publico.teachersBody.ReadProfessorshipsAndResponsibilitiesByExecutionDegreeAndExecutionPeriod.java

@Atomic
public static List run(String executionDegreeId, Integer semester, Integer teacherType)
        throws FenixServiceException {

    final ExecutionDegree executionDegree = FenixFramework.getDomainObject(executionDegreeId);

    List professorships;//from  www.j  a  v  a2 s  .co m
    if (semester.intValue() == 0) {
        professorships = Professorship.readByDegreeCurricularPlanAndExecutionYear(
                executionDegree.getDegreeCurricularPlan(), executionDegree.getExecutionYear());
    } else {
        ExecutionSemester executionSemester = executionDegree.getExecutionYear()
                .getExecutionSemesterFor(semester);
        professorships = Professorship.readByDegreeCurricularPlanAndExecutionPeriod(
                executionDegree.getDegreeCurricularPlan(), executionSemester);
    }

    List responsibleFors = getResponsibleForsByDegree(executionDegree);

    List detailedProfessorships = getDetailedProfessorships(professorships, responsibleFors, teacherType);

    // Cleaning out possible null elements inside the list
    Iterator itera = detailedProfessorships.iterator();
    while (itera.hasNext()) {
        Object dp = itera.next();
        if (dp == null) {
            itera.remove();
        }
    }

    Collections.sort(detailedProfessorships, new Comparator() {

        @Override
        public int compare(Object o1, Object o2) {
            DetailedProfessorship detailedProfessorship1 = (DetailedProfessorship) o1;
            DetailedProfessorship detailedProfessorship2 = (DetailedProfessorship) o2;
            int result = detailedProfessorship1.getInfoProfessorship().getInfoExecutionCourse().getExternalId()
                    .compareTo(detailedProfessorship2.getInfoProfessorship().getInfoExecutionCourse()
                            .getExternalId());
            if (result == 0 && (detailedProfessorship1.getResponsibleFor().booleanValue()
                    || detailedProfessorship2.getResponsibleFor().booleanValue())) {
                if (detailedProfessorship1.getResponsibleFor().booleanValue()) {
                    return -1;
                }
                if (detailedProfessorship2.getResponsibleFor().booleanValue()) {
                    return 1;
                }
            }

            return result;
        }

    });

    List result = new ArrayList();
    Iterator iter = detailedProfessorships.iterator();
    List temp = new ArrayList();
    while (iter.hasNext()) {
        DetailedProfessorship detailedProfessorship = (DetailedProfessorship) iter.next();
        if (temp.isEmpty() || ((DetailedProfessorship) temp.get(temp.size() - 1)).getInfoProfessorship()
                .getInfoExecutionCourse()
                .equals(detailedProfessorship.getInfoProfessorship().getInfoExecutionCourse())) {
            temp.add(detailedProfessorship);
        } else {
            result.add(temp);
            temp = new ArrayList();
            temp.add(detailedProfessorship);
        }
    }
    if (!temp.isEmpty()) {
        result.add(temp);
    }
    return result;
}

From source file:edu.gsgp.utils.Utils.java

/**
 * Generates an array with a number of folds defined by the user. Each fold
 * contains dataset.size() / numFolds instances.
 * @param numFolds Number of folds//from  ww w.j  a  va 2s.co  m
 * @param dataset Input datase
 * @param rnd Random number generator
 * @return An array of folds
 */
public static Dataset[] getFoldSampling(int numFolds, Dataset dataset, MersenneTwister rnd) {
    Dataset[] folds = new Dataset[numFolds];
    ArrayList<Instance> dataCopy = dataset.softClone();
    int foldIndex = 0;
    if (rnd == null) {
        Iterator<Instance> it = dataCopy.iterator();
        while (it.hasNext()) {
            if (folds[foldIndex] == null)
                folds[foldIndex] = new Dataset();
            folds[foldIndex].add(it.next());
            it.remove();
            if (foldIndex < numFolds - 1)
                foldIndex++;
            else
                foldIndex = 0;
        }
    } else {
        while (!dataCopy.isEmpty()) {
            if (folds[foldIndex] == null)
                folds[foldIndex] = new Dataset();
            folds[foldIndex].add(dataCopy.remove(rnd.nextInt(dataCopy.size())));
            if (foldIndex < numFolds - 1)
                foldIndex++;
            else
                foldIndex = 0;
        }
    }
    return folds;
}

From source file:de.laures.cewolf.util.Renderer.java

public static void removeLegend(JFreeChart chart) {
    List subTitles = chart.getSubtitles();
    Iterator iter = subTitles.iterator();
    while (iter.hasNext()) {
        Object o = iter.next();/*from  w  w  w.j  a v a  2s.c  om*/
        if (o instanceof LegendTitle) {
            iter.remove();
            break;
        }
    }
}

From source file:Main.java

public static final String postData(String url, HashMap<String, String> params) {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    String outputString = null;/* w w w .  j a  v a2s .  c  o m*/

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(params.size());
        Iterator it = params.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry pair = (Map.Entry) it.next();
            nameValuePairs.add(new BasicNameValuePair((String) pair.getKey(), (String) pair.getValue()));
            System.out.println(pair.getKey() + " = " + pair.getValue());
            it.remove(); // avoids a ConcurrentModificationException
        }
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpURLConnection.HTTP_OK) {
            byte[] result = EntityUtils.toByteArray(response.getEntity());
            outputString = new String(result, "UTF-8");
        }

    } catch (ClientProtocolException e) {
        Log.i(CLASS_NAME, "Client protocolException happened: " + e.getMessage());
    } catch (IOException e) {
        Log.i(CLASS_NAME, "Client IOException happened: " + e.getMessage());
    } catch (NetworkOnMainThreadException e) {
        Log.i(CLASS_NAME, "Client NetworkOnMainThreadException happened: " + e.getMessage());
        e.printStackTrace();
    } catch (Exception e) {
        Log.i(CLASS_NAME, "Unknown exeception: " + e.getMessage());
    }
    return outputString;
}

From source file:com.cyberway.issue.net.PublicSuffixes.java

/**
 * Reads a file of the format promulgated by publicsuffix.org, ignoring
 * comments and '!' exceptions/notations, converting domain segments to
 * SURT-ordering. Leaves glob-style '*' wildcarding in place. Returns sorted
 * list of unique SURT-ordered prefixes.
 * /*from w w w . ja v a  2  s .  c om*/
 * @param reader
 * @return
 * @throws IOException
 */
public static List<String> readPublishedFileToSurtList(BufferedReader reader) throws IOException {
    String line;
    List<String> list = new ArrayList<String>();
    while ((line = reader.readLine()) != null) {

        // discard whitespace, empty lines, comments, exceptions
        line = line.trim();
        if (line.length() == 0 || line.startsWith("//")) {
            continue;
        }
        // discard utf8 notation after entry
        line = line.split("\\s+")[0];
        line = line.toLowerCase();

        // SURT-order domain segments
        String[] segs = line.split("\\.");
        StringBuilder surtregex = new StringBuilder();
        for (int i = segs.length - 1; i >= 0; i--) {
            if (segs[i].length() > 0) {
                // current list has a stray '?' in a .no domain
                String fixed = segs[i].replaceAll("\\?", "_");
                // replace '!' with '+' to indicate lookahead-for-exceptions
                // (gets those to sort before '*' at later build-step)
                fixed = fixed.replaceAll("!", "+");
                surtregex.append(fixed + ",");
            }
        }
        list.add(surtregex.toString());
    }

    Collections.sort(list);
    // uniq
    String last = "";
    Iterator<String> iter = list.iterator();
    while (iter.hasNext()) {
        String s = iter.next();
        if (s.equals(last)) {
            iter.remove();
            continue;
        }
        last = s;
        //            System.out.println(s);
    }
    return list;
}