Example usage for java.util ArrayList iterator

List of usage examples for java.util ArrayList iterator

Introduction

In this page you can find the example usage for java.util ArrayList iterator.

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this list in proper sequence.

Usage

From source file:uk.ac.cam.cl.dtg.util.locations.PostCodeIOLocationResolver.java

/**
 * @param unknownPostCodes/*from w  w w .jav a 2s . co  m*/
 *            - a list of postcodes not exceeding maxRequests in length
 * @return - the results
 * @throws LocationServerException
 *             - if there was an issue with the service
 */
@SuppressWarnings("unchecked")
private List<PostCode> submitPostCodeRequest(final List<String> unknownPostCodes)
        throws LocationServerException {

    if (unknownPostCodes.size() > POSTCODEIO_MAX_REQUESTS) {
        throw new IllegalArgumentException(
                String.format("Number of postcodes cannot be bigger than %d!", POSTCODEIO_MAX_REQUESTS));
    }

    StringBuilder sb = new StringBuilder();
    sb.append("{ \"postcodes\" : [");
    for (int i = 0; i < unknownPostCodes.size(); i++) {
        sb.append("\"");
        sb.append(unknownPostCodes.get(i));
        sb.append("\"");
        if (i < unknownPostCodes.size() - 1) {
            sb.append(", ");
        }
    }
    sb.append("] }");

    String requestJson = sb.toString();

    HashMap<String, Object> response = new HashMap<String, Object>();

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    StringEntity requestEntity;
    try {
        requestEntity = new StringEntity(requestJson);
        httppost.addHeader("Content-Type", "application/json");
        httppost.setEntity(requestEntity);
        HttpResponse httpresponse = httpclient.execute(httppost);
        HttpEntity entity = httpresponse.getEntity();
        String jsonResponse = EntityUtils.toString(entity);
        ObjectMapper objectMapper = new ObjectMapper();

        response = objectMapper.readValue(jsonResponse, HashMap.class);

    } catch (UnsupportedEncodingException | JsonParseException | JsonMappingException e) {
        String error = "Unable to parse postcode location response " + e.getMessage();
        log.error(error);
        throw new LocationServerException(error);
    } catch (IOException e) {
        String error = "Unable to read postcode location response " + e.getMessage();
        log.error(error);
        throw new LocationServerException(error);
    }

    List<PostCode> returnList = Lists.newArrayList();
    int responseCode = (int) response.get("status");
    if (responseCode == HttpResponseStatus.OK.getCode()) {
        ArrayList<HashMap<String, Object>> responseResult = (ArrayList<HashMap<String, Object>>) response
                .get("result");

        Iterator<HashMap<String, Object>> it = responseResult.iterator();
        while (it.hasNext()) {
            Map<String, Object> item = it.next();
            HashMap<String, Object> postCodeDetails = (HashMap<String, Object>) item.get("result");

            if (postCodeDetails != null) {
                Double sourceLat = (Double) postCodeDetails.get("latitude");
                Double sourceLon = (Double) postCodeDetails.get("longitude");
                PostCode postcode = new PostCode((String) item.get("query"), sourceLat, sourceLon);
                returnList.add(postcode);
            }

        }
    }

    return returnList;
}

From source file:net.phyloviz.mstsstatistics.Runner.java

@Override
public void run() {

    gr.getPanel().appendWithDate("MST Statistics started...\n");
    gr.getPanel().flush();//from  ww  w .java2 s .c om

    System.out.println("MST Statistics started... \n");

    List<EdgeMST> edgesList = new ArrayList<EdgeMST>();
    Collection<GOeBurstClusterWithStats> groups = gr.getClustering();
    Iterator<GOeBurstClusterWithStats> gIter = groups.iterator();

    while (gIter.hasNext()) {

        GOeBurstClusterWithStats g = gIter.next();
        ArrayList<net.phyloviz.goeburst.cluster.Edge<GOeBurstNodeExtended>> gEdges = g.getEdges();
        Iterator<net.phyloviz.goeburst.cluster.Edge<GOeBurstNodeExtended>> geIter = gEdges.iterator();
        while (geIter.hasNext()) {
            Edge<GOeBurstNodeExtended> e = geIter.next();
            int level = gr.getDistance().level(e);
            EdgeMST ne = new EdgeMST(e.getU(), e.getV(), level, e.visible());
            edgesList.add(ne);
        }
        if (edgesList.isEmpty()) {
            continue;
        }

        gr.getPanel().appendWithDate("Processing CC " + g.getID() + "\n");
        double nmsts = calcNumberMSTs(edgesList, gr);

        /*      DecimalFormat df = new DecimalFormat("0.######E0");
         DecimalFormat pf = new DecimalFormat("#.##");*/
        //         if (nmsts < Double.POSITIVE_INFINITY) {
        gr.getPanel().append("CC " + g.getID() + " has 10^ " + nmsts + " MSTs\nEdge stats:\n");

        Iterator<EdgeMST> ei = edgesList.iterator();
        while (ei.hasNext()) {
            EdgeMST e = ei.next();
            if (e.isVisible()) {
                gr.getPanel()
                        .append(e.getSourceNode().getID() + " - " + e.getDestNode().getID() + ", level: "
                                + e.getLevel() + ", freq: " + (Math.pow(10, e.getNmsts()) * 100.0) + "% ("
                                + e.getNmsts() + ")\n");
                gr.getPanel().flush();

                String source = String.valueOf(e.getSourceNode().getID());
                String dest = String.valueOf(e.getDestNode().getID());
                String edge = source + dest;
                result.put(edge, e.getNmsts());

            }

        }
        /*   } else {
         gr.getPanel().append("CC " + g.getID() + " has more than 1E100 MSTs\nSkipping edge stats.\n");   
         }*/

        gr.getPanel().append("\n");
        gr.getPanel().flush();

        edgesList.clear();
    }
    gr.getPanel().appendWithDate("MST Statistics done.\n");
    gr.getPanel().flush();

    gr.setEdgestats(result);
}

From source file:com.liferay.alloy.tools.transformer.AlloyDocsTransformer.java

private ArrayList<Attribute> _getComponentAttributes(String className, String attributeType) {

    Set<Attribute> attributes = new HashSet<Attribute>();

    ArrayList<String> hierarchy = getComponentHierarchy(className);

    try {/*from ww  w. ja v a 2s.  c  o m*/
        for (String parentClass : hierarchy) {
            ArrayList<JSONObject> classItems = _getClassItems(parentClass, attributeType);

            Iterator<JSONObject> it = classItems.iterator();

            while (it.hasNext()) {
                JSONObject attributeJSON = it.next();

                String name = attributeJSON.getString("name");

                String javaScriptType = Convert.toString(JSONUtil.getString(attributeJSON, "type"),
                        _DEFAULT_JAVASCRIPT_TYPE);

                String outputJavaType = TypeUtil.getOutputJavaType(javaScriptType, true);

                String defaultValue = DefaultValueUtil.getDefaultValue(outputJavaType,
                        JSONUtil.getString(attributeJSON, "default"));

                String description = Convert.toString(JSONUtil.getString(attributeJSON, "description"),
                        StringPool.EMPTY);

                String readOnlyString = JSONUtil.getString(attributeJSON, "readonly");

                boolean readOnly = false;

                if (readOnlyString != null) {
                    readOnly = readOnlyString.equals(StringPool.EMPTY) || Boolean.parseBoolean(readOnlyString);
                }

                boolean required = Convert.toBoolean(JSONUtil.getString(attributeJSON, "required"), false);

                Attribute attribute = new Attribute();

                attribute.setName(name);
                attribute.setJavaScriptType(javaScriptType);
                attribute.setDefaultValue(defaultValue);
                attribute.setDescription(description);
                attribute.setRequired(required);
                attribute.setReadOnly(readOnly);

                attributes.add(attribute);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    ArrayList<Attribute> sortedAttributes = new ArrayList<Attribute>(attributes);

    Collections.sort(sortedAttributes);

    return sortedAttributes;
}

From source file:com.ipo.wiimote.SpeechRecognizer.java

/**
 * Handle the results from the recognition activity.
 *//*from   w w  w.  ja  v a 2  s .co  m*/
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == Activity.RESULT_OK) {
        // Fill the list view with the strings the recognizer thought it could have heard
        ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        float[] confidence = data.getFloatArrayExtra(RecognizerIntent.EXTRA_CONFIDENCE_SCORES);

        if (confidence != null) {
            Log.d(LOG_TAG, "confidence length " + confidence.length);
            Iterator<String> iterator = matches.iterator();
            int i = 0;
            while (iterator.hasNext()) {
                Log.d(LOG_TAG, "Match = " + iterator.next() + " confidence = " + confidence[i]);
                i++;
            }
        } else {
            Log.d(LOG_TAG, "No confidence" + "");
        }

        ReturnSpeechResults(requestCode, matches);
    } else {
        // Failure - Let the caller know
        ReturnSpeechFailure(resultCode);
    }

    super.onActivityResult(requestCode, resultCode, data);
}

From source file:net.phyloviz.mstsstatistics.Runner.java

private double calcNumberMSTs(List edgesList, GOeBurstResult sgr) {

    Collections.sort(edgesList);//from   ww w .j ava2  s.  c o  m

    double nmsts = 0;

    int mapid;

    //Passo 1 - Descobrir o MaxId Inicial
    int maxid = findMaxId(edgesList);
    SparseDoubleMatrix2D matrix = new SparseDoubleMatrix2D(maxid + 1, maxid + 1);
    matrix.assign(0);

    DisjointSet ds = new DisjointSet(maxid);

    int[] map = new int[maxid + 1];
    for (int i = 0; i <= maxid; i++) {
        map[i] = i;
    }

    int[] mapaux = new int[maxid + 1];
    for (int i = 0; i <= maxid; i++) {
        mapaux[i] = -1;
    }

    //Passo 2 - Varrer arcos do nivel L, preenchendo a matriz
    Iterator<EdgeMST> eIter = edgesList.iterator();

    EdgeMST e = eIter.next();
    int level = (e != null) ? e.getLevel() : 1;

    ArrayList<Integer> vaux = new ArrayList<Integer>(maxid + 1);

    int prev = 0;
    int now = 0;

    while (true) {
        if (e != null && e.getLevel() == level) {
            int u = e.getSource();
            int v = e.getDest();
            if (!vaux.contains(u)) {
                vaux.add(u);
            }
            if (!vaux.contains(v)) {
                vaux.add(v);
            }
            //Preenchimento da Matriz
            int s = map[u];
            int d = map[v];

            matrix.setQuick(s, d, matrix.getQuick(s, d) - 1);
            matrix.setQuick(d, s, matrix.getQuick(d, s) - 1);
            matrix.setQuick(s, s, matrix.getQuick(s, s) + 1);
            matrix.setQuick(d, d, matrix.getQuick(d, d) + 1);

            if (!ds.sameSet(u, v)) {
                ds.unionSet(u, v);
            }

            now++;

            try {
                e = eIter.next();
            } catch (NoSuchElementException ex) {
                e = null;
            }

        } else if (prev != now) {
            mapid = 0;
            for (int i = 0; i <= maxid; i++) {
                int setid = ds.findSet(i);
                if (mapaux[setid] == -1) {
                    mapaux[setid] = mapid;
                    mapaux[i] = mapid;
                    mapid++;
                } else {
                    mapaux[i] = mapaux[setid];
                }
            }

            ArrayList[] calcDet = new ArrayList[mapid];
            for (int i = 0; i < calcDet.length; i++) {
                calcDet[i] = new ArrayList<Integer>();
            }

            for (int i = 0; i < vaux.size(); i++) {
                if (!calcDet[mapaux[vaux.get(i)]].contains(map[vaux.get(i)])) {
                    calcDet[mapaux[vaux.get(i)]].add(map[vaux.get(i)]);
                }
            }

            sgr.getPanel().appendWithDate("Level " + level + "\n");

            double[] calcNMstsDet = new double[mapid];
            for (int i = 0; i < calcDet.length; i++) {

                if (!calcDet[i].isEmpty()) {

                    int[] vgraph = new int[calcDet[i].size()];
                    ArrayList<Integer> graph = (ArrayList<Integer>) calcDet[i];
                    Iterator<Integer> gIter = graph.iterator();
                    int index = 0;
                    while (gIter.hasNext()) {
                        vgraph[index++] = gIter.next();
                    }

                    double det = 0.0;
                    LUDecomposition tempMax = new LUDecomposition(
                            (matrix.viewSelection(ArrayUtils.subarray(vgraph, 0, vgraph.length - 1),
                                    ArrayUtils.subarray(vgraph, 0, vgraph.length - 1))));
                    DoubleMatrix2D max = tempMax.getU();
                    System.out.println(max.rows());
                    for (int k = 0; k < max.rows(); k++) {
                        det += Math.log10(Math.abs(max.get(k, k)));
                    }

                    if (det == 0) {
                        det = 1;
                    }

                    sgr.getPanel().append("View: " + Arrays.toString(vgraph) + "\n");
                    sgr.getPanel().append("Det: " + det + "\n");
                    sgr.getPanel().flush();

                    calcNMstsDet[i] = det;
                    nmsts = nmsts + det;

                }
            }

            calcEdgesNMSTs(edgesList, prev, now, map, mapaux, calcDet, matrix, calcNMstsDet);

            prev = now;
            if (e == null) {
                break;
            }

            matrix = new SparseDoubleMatrix2D(mapid, mapid);
            matrix.assign(0);
            map = mapaux;
            mapaux = new int[maxid + 1];
            for (int i = 0; i <= maxid; i++) {
                mapaux[i] = -1;
            }
            //Passa para o nvel seguinte
            level++;
            vaux = new ArrayList<Integer>(mapid);
        } else { // Se prev==now a lista  vazia e passamos para o nvel seguinte
            level++;
        }
    }

    return nmsts;
}

From source file:de.knowwe.rdf2go.utils.ResultTableModel.java

@Override
public Iterator<TableRow> iterator() {
    if (comparators.isEmpty()) {
        return rows.iterator();
    } else {//from w w  w.j  av a  2s  .c  om
        ArrayList<TableRow> tableRows = new ArrayList<>(rows);
        Collections.reverse(comparators);
        for (Comparator<TableRow> comparator : comparators) {
            Collections.sort(tableRows, comparator);
        }
        return tableRows.iterator();
    }
}

From source file:RemoveDuplicateFiles.java

public static void addActionHandlers(Stage primaryStage) {
    //Sort Files Button Pressed.
    sortFilesButton.setOnAction((ActionEvent event) -> {
        //Move to the SortFiles window
        new FileSort(primaryStage);
    });/* ww w .j av a  2  s .com*/

    //Batch Rename Button Pressed
    batchRenameButton.setOnAction((ActionEvent event) -> {
        //Move to the BatchRename window
        new BatchRename(primaryStage);
    });

    //Action Handler: remove the duplicate files in the directory.
    rmvButton.setOnAction((ActionEvent event) -> {
        //Clear the actionTarget
        actionTarget.setFill(Color.BLACK);
        actionTarget.setText("");

        //Make sure we have the right path
        selectedDirectory = new File(address.getText());

        if (selectedDirectory != null && selectedDirectory.isDirectory()) {
            //Grab the list of file types from the textbox
            String[] extensions = UtilFunctions.parseFileTypes(fileTypes.getText());

            //Grab the list of files in the selectedDirectory
            List<File> files = (List<File>) FileUtils.listFiles(selectedDirectory, extensions, true);
            HashSet<String> hashCodes = new HashSet<>();
            ArrayList<File> duplicates = new ArrayList<>();

            //Progress reporting values
            actionTarget.setFill(Color.BLACK);
            int totalFileCount = files.size();
            int filesProcessed = 0;

            //Find the duplicate files
            for (File f : files) {
                try {
                    //Update the status
                    filesProcessed++;
                    actionTarget.setText("Processing file " + filesProcessed + " of " + totalFileCount);

                    //Grab the file's hash code
                    String hash = UtilFunctions.makeHash(f);

                    //If we already have a file matching that hash code
                    if (hashCodes.contains(hash)) {
                        //Add the file to the list of files to be deleted
                        duplicates.add(f);
                    } else {
                        hashCodes.add(hash);
                    }

                } catch (Exception except) {
                }
            } //End for

            //Progress reporting
            filesProcessed = 0;
            totalFileCount = duplicates.size();
            Iterator<File> itr = duplicates.iterator();

            //Remove the duplicate files
            while (itr.hasNext()) {
                try {
                    //Update the status
                    filesProcessed++;
                    actionTarget.setText("Deleting file " + filesProcessed + " of " + totalFileCount);

                    //Grab the file
                    File file = itr.next();

                    if (!file.delete()) {
                        JOptionPane.showMessageDialog(null, file.getPath() + " not deleted.");
                    }

                } catch (Exception except) {
                }
            } //End while

            actionTarget.setText("Deleted: " + filesProcessed);

        } else {
            actionTarget.setFill(Color.FIREBRICK);
            actionTarget.setText("Invalid directory.");
        }
    });

}

From source file:net.bitnine.agensgraph.graph.property.JsonArray.java

public Iterator<Object> iterator() {
    ArrayList<Object> l = new ArrayList<>();
    for (Object elem : array) {
        if (elem instanceof JSONObject) {
            l.add(new JsonObject((JSONObject) elem));
        } else if (elem instanceof JSONArray) {
            l.add(new JsonArray((JSONArray) elem));
        } else {//from   www . j  a va2s .c om
            l.add(elem);
        }
    }
    return l.iterator();
}

From source file:com.denkbares.semanticcore.utils.ResultTableModel.java

@NotNull
@Override//from  w  ww  . j  a  v  a  2  s  . com
public Iterator<TableRow> iterator() {
    if (comparators.isEmpty()) {
        return rows.iterator();
    } else {
        ArrayList<TableRow> tableRows = new ArrayList<>(rows);
        Collections.reverse(comparators);
        for (Comparator<TableRow> comparator : comparators) {
            tableRows.sort(comparator);
        }
        return tableRows.iterator();
    }
}

From source file:eulermind.importer.LineNode.java

private static void brokenSentencesToTree(LineNode root) {

    //????//from   w  w  w  .ja va 2  s  .  co  m
    ArrayList<Integer> lineStarts = new ArrayList<>();
    String combinedLine = "";
    for (int i = 0; i < root.getChildCount(); i++) {
        lineStarts.add(combinedLine.length());
        combinedLine += root.getChildAt(i).m_trimLine + (i < root.getChildCount() - 1 ? " " : "");
    }
    lineStarts.add(combinedLine.length()); //

    //???
    BreakIterator boundary = BreakIterator.getSentenceInstance(getStringULocale(combinedLine));
    boundary.setText(combinedLine);

    ArrayList<Integer> icuSentenceStarts = new ArrayList<>();
    for (int icuSentenceStart = boundary.first(); icuSentenceStart != BreakIterator.DONE; //icuSentenceStartcombinedLine.length()
            icuSentenceStart = boundary.next()) {

        icuSentenceStarts.add(icuSentenceStart);
    }

    //???
    Iterator<Integer> lineStartIter = lineStarts.iterator();
    while (lineStartIter.hasNext()) {
        Integer lineStart = lineStartIter.next();
        if (!(icuSentenceStarts.contains(lineStart - 1) || icuSentenceStarts.contains(lineStart))) {
            lineStartIter.remove();
        }
    }

    assert (lineStarts.contains(combinedLine.length()));

    //???
    //1 ????, ?linsStarts.size == 2 (0combinedLine.length())  root.getChildCount >= 2
    //2 ????
    if (lineStarts.size() == 2 && root.getChildCount() >= 2 || lineStarts.size() - 1 == root.getChildCount()) {
        return;
    }

    assert (lineStarts.size() - 1 < root.getChildCount());

    root.removeAllChildren();

    //??
    // ??
    // ????
    for (int lineIdx = 0; lineIdx < lineStarts.size() - 1; lineIdx++) {
        int lineStart = lineStarts.get(lineIdx);
        int lineEnd = lineStarts.get(lineIdx + 1);

        int firstSentenceInThisLine = 0;
        int firstSentenceInNextLine = 0;

        for (firstSentenceInThisLine = 0; firstSentenceInThisLine < icuSentenceStarts.size()
                - 1; firstSentenceInThisLine++) {
            int sentenceStart = icuSentenceStarts.get(firstSentenceInThisLine);
            if (lineStart <= sentenceStart && sentenceStart < lineEnd) {
                break;
            }
        }

        for (firstSentenceInNextLine = firstSentenceInThisLine
                + 1; firstSentenceInNextLine < icuSentenceStarts.size() - 1; firstSentenceInNextLine++) {
            int sentenceStart = icuSentenceStarts.get(firstSentenceInNextLine);
            if (sentenceStart >= lineEnd) {
                break;
            }
        }

        assert firstSentenceInNextLine - firstSentenceInThisLine >= 1;

        if (firstSentenceInNextLine - firstSentenceInThisLine == 1) {
            int sentenceStart = icuSentenceStarts.get(firstSentenceInThisLine);
            int sentenceEnd = icuSentenceStarts.get(firstSentenceInNextLine);

            LineNode lineNode = new LineNode(combinedLine.substring(sentenceStart, sentenceEnd));
            root.add(lineNode);

        } else {
            LineNode lineNode = new LineNode("p");
            for (int sentence = firstSentenceInThisLine; sentence < firstSentenceInNextLine; sentence++) {
                int sentenceStart = icuSentenceStarts.get(sentence);
                int sentenceEnd = icuSentenceStarts.get(sentence + 1);

                LineNode sentenceNode = new LineNode(combinedLine.substring(sentenceStart, sentenceEnd));
                lineNode.add(sentenceNode);
            }
            root.add(lineNode);
        }
    }
    //s_logger.info("ccccccccccc: {}", lineTreeToString(root));
}