Example usage for java.util Set iterator

List of usage examples for java.util Set iterator

Introduction

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

Prototype

Iterator<E> iterator();

Source Link

Document

Returns an iterator over the elements in this set.

Usage

From source file:Main.java

/**
 * Returns <code>true</code> if both lists are the same?
 *
 * @param set1/*from   w  ww.j  ava 2  s .  c o m*/
 * @param set2
 * @return
 */
@SuppressWarnings("ObjectEquality")
public static boolean same(final Set set1, final Set set2) {

    if (set1 == null || set2 == null) {
        return false;
    }
    if (set1.size() != set2.size()) {
        return false;
    }
    if (set1 == set2) {
        return true;
    }
    final Iterator iter1 = set1.iterator();
    final Iterator iter2 = set2.iterator();
    while (iter1.hasNext()) {
        final Object o1 = iter1.next();
        final Object o2 = iter2.next();
        if (!o1.equals(o2)) {
            return false;
        }
    }
    return true;
}

From source file:com.netflix.nicobar.core.module.ScriptModuleUtils.java

/**
 * Convert a ScriptModule to its compiled equivalent ScriptArchive.
 * <p>/*from  www .j  a  v  a2 s . c  o  m*/
 * A jar script archive is created containing compiled bytecode
 * from a script module, as well as resources and other metadata from
 * the source script archive.
 * <p>
 * This involves serializing the class bytes of all the loaded classes in
 * the script module, as well as copying over all entries in the original
 * script archive, minus any that have excluded extensions. The module spec
 * of the source script archive is transferred as is to the target bytecode
 * archive.
 *
 * @param module the input script module containing loaded classes
 * @param jarPath the path to a destination JarScriptArchive.
 * @param excludeExtensions a set of extensions with which
 *        source script archive entries can be excluded.
 *
 * @throws Exception
 */
public static void toCompiledScriptArchive(ScriptModule module, Path jarPath, Set<String> excludeExtensions)
        throws Exception {
    ScriptArchive sourceArchive = module.getSourceArchive();
    JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jarPath.toFile()));
    try {
        // First copy all resources (excluding those with excluded extensions)
        // from the source script archive, into the target script archive
        for (String archiveEntry : sourceArchive.getArchiveEntryNames()) {
            URL entryUrl = sourceArchive.getEntry(archiveEntry);
            boolean skip = false;
            for (String extension : excludeExtensions) {
                if (entryUrl.toString().endsWith(extension)) {
                    skip = true;
                    break;
                }
            }

            if (skip)
                continue;

            InputStream entryStream = entryUrl.openStream();
            byte[] entryBytes = IOUtils.toByteArray(entryStream);
            entryStream.close();

            jarStream.putNextEntry(new ZipEntry(archiveEntry));
            jarStream.write(entryBytes);
            jarStream.closeEntry();
        }

        // Now copy all compiled / loaded classes from the script module.
        Set<Class<?>> loadedClasses = module.getModuleClassLoader().getLoadedClasses();
        Iterator<Class<?>> iterator = loadedClasses.iterator();
        while (iterator.hasNext()) {
            Class<?> clazz = iterator.next();
            String classPath = clazz.getName().replace(".", "/") + ".class";
            URL resourceURL = module.getModuleClassLoader().getResource(classPath);
            if (resourceURL == null) {
                throw new Exception("Unable to find class resource for: " + clazz.getName());
            }

            InputStream resourceStream = resourceURL.openStream();
            jarStream.putNextEntry(new ZipEntry(classPath));
            byte[] classBytes = IOUtils.toByteArray(resourceStream);
            resourceStream.close();
            jarStream.write(classBytes);
            jarStream.closeEntry();
        }

        // Copy the source moduleSpec, but tweak it to specify the bytecode compiler in the
        // compiler plugin IDs list.
        ScriptModuleSpec moduleSpec = sourceArchive.getModuleSpec();
        ScriptModuleSpec.Builder newModuleSpecBuilder = new ScriptModuleSpec.Builder(moduleSpec.getModuleId());
        newModuleSpecBuilder.addCompilerPluginIds(moduleSpec.getCompilerPluginIds());
        newModuleSpecBuilder.addCompilerPluginId(BytecodeLoadingPlugin.PLUGIN_ID);
        newModuleSpecBuilder.addMetadata(moduleSpec.getMetadata());
        newModuleSpecBuilder.addModuleDependencies(moduleSpec.getModuleDependencies());

        // Serialize the modulespec with GSON and its default spec file name
        ScriptModuleSpecSerializer specSerializer = new GsonScriptModuleSpecSerializer();
        String json = specSerializer.serialize(newModuleSpecBuilder.build());
        jarStream.putNextEntry(new ZipEntry(specSerializer.getModuleSpecFileName()));
        jarStream.write(json.getBytes(Charsets.UTF_8));
        jarStream.closeEntry();
    } finally {
        if (jarStream != null) {
            jarStream.close();
        }
    }
}

From source file:com.ibm.mobilefirstplatform.clientsdk.cordovaplugins.core.CDVMFPLogger.java

public static JSONObject HashMapToJSONObject(HashMap<String, LEVEL> pairs) {
    if (pairs == null) {
        return new JSONObject();
    }//from ww w . j a v  a 2s .  c  o  m

    Set<String> set = pairs.keySet();
    JSONObject jsonObj = new JSONObject();
    @SuppressWarnings("rawtypes")
    Iterator it = set.iterator();
    while (it.hasNext()) {
        String n = (String) it.next();
        try {
            jsonObj.put(n, pairs.get(n).toString());
        } catch (JSONException e) {
            // not possible
        }
    }
    return jsonObj;
}

From source file:com.sixt.service.framework.protobuf.ProtobufUtil.java

private static void cleanJsonObject(JsonObject element) {
    Set<Map.Entry<String, JsonElement>> members = element.entrySet();
    Iterator<Map.Entry<String, JsonElement>> iter = members.iterator();
    while (iter.hasNext()) {
        Map.Entry<String, JsonElement> member = iter.next();
        JsonElement value = member.getValue();
        cleanJsonElement(value);//from  ww w  .  jav  a  2s  . c  o  m
    }
}

From source file:com.ebay.erl.mobius.core.JobSetup.java

/**
 * specify the columns that a mapper needs to emit.
 *//*from   ww w .j  a  v a  2  s  .co m*/
public static void setupProjections(JobConf job, Dataset dataset, byte datasetID, Column... projections) {
    StringBuffer sortedColumns = new StringBuffer();

    // dedupe the projection input column name and then sort it.

    Set<String> uniqueColumnNames = new TreeSet<String>(String.CASE_INSENSITIVE_ORDER);

    for (Column aProjection : projections) {
        uniqueColumnNames.add(aProjection.getInputColumnName());
    }

    Iterator<String> it = uniqueColumnNames.iterator();
    while (it.hasNext()) {
        sortedColumns.append(it.next());
        if (it.hasNext())
            sortedColumns.append(",");
    }
    job.set(datasetID + ".value.columns", sortedColumns.toString());

    // for Mapper only task
    StringBuffer originalOrder = new StringBuffer();
    for (int i = 0; i < projections.length; i++) {
        originalOrder.append(projections[i].getInputColumnName());
        if (i < projections.length - 1)
            originalOrder.append(",");
    }
    job.set(datasetID + ".columns.in.original.order", originalOrder.toString());
}

From source file:in.mycp.utils.Commons.java

public static Workflow createNewWorkflow(ProcessInstance pi, Integer assetId, String assetType) {

    Workflow workflow = new Workflow();
    workflow.setProcessId(pi.getId());//from   ww w  .  ja va 2  s. c om
    String activityName = "";
    Set<String> activityNames = pi.findActiveActivityNames();
    for (Iterator iterator = activityNames.iterator(); iterator.hasNext();) {
        String string = (String) iterator.next();
        activityName = string;
        break;
    }
    workflow.setStatus(activityName);
    workflow.setAssetId(assetId);
    workflow.setAssetType(assetType);
    workflow.setUser(getCurrentUser());
    return workflow.merge();
}

From source file:com.opengamma.analytics.financial.interestrate.InterestRateCurveSensitivityUtils.java

/**
 * Takes a map of curve sensitivities (i.e. a map between curve names and a unordered lists of pairs of times and sensitivities)
 *  and returns a similar map where the lists order by ascending time, and with sensitivities that occur at the same time netted
 *  (zero net sensitivities are removed)
 * @param old A map between curve names and unordered lists of pairs of times and sensitivities
 * @param relTol Relative tolerance - if the net divided by gross sensitivity is less than this it is ignored/removed
 * @param absTol Absolute tolerance  - is the net sensitivity is less than this it is ignored/removed
 * @return A map between curve names and time ordered netted lists
 *//* w w  w .j ava 2s  .  co m*/
public static Map<String, List<DoublesPair>> clean(final Map<String, List<DoublesPair>> old,
        final double relTol, final double absTol) {
    final Map<String, List<DoublesPair>> res = new HashMap<String, List<DoublesPair>>();
    final Set<Entry<String, List<DoublesPair>>> sense = old.entrySet();
    final Iterator<Entry<String, List<DoublesPair>>> interator = sense.iterator();
    while (interator.hasNext()) {
        final Entry<String, List<DoublesPair>> entry = interator.next();
        res.put(entry.getKey(), clean(entry.getValue(), relTol, absTol));
    }
    return res;
}

From source file:com.ecarride.App.java

public static void sendEmailToDrivers(Set<TlcDriver> tlcDrivers) throws MessagingException {
    Iterator<TlcDriver> iterator = tlcDrivers.iterator();
    Map<String, String> result = new LinkedHashMap<>();
    String driverAlert = "";
    while (iterator.hasNext()) {
        TlcDriver tlcDriver = iterator.next();
        if (tlcDriver.isInTrouble()) {
            inTroubleNum++;/*w ww .  j  a va2 s  . co m*/
            driverAlert += "<b>Your work has been suspended due to a driver and/or vehicle status change. <br>"
                    + "Please contact your base. <br><br> </b>  Your info: <br>";
            driverAlert += "Name: " + tlcDriver.getDriver().getFirstName() + " "
                    + tlcDriver.getDriver().getLastName() + " <br>" + "TLC_FHV_License_Number: "
                    + tlcDriver.getDriver().getDriverTlcFhvLicenseNum() + "  <br>"
                    + "TLC_FHV_Vehicle_License_Number: "
                    + tlcDriver.getTaxiVehicle().getVehicleTlcFhvLicenseNum() + "<br> <br>";
            driverAlert += "Reason: <br>";
            if (!tlcDriver.isActiveInFhvDrivers()) {
                driverAlert += "You are not a <b> For-Hire Vehicles FHV Active Driver. Please contact your base</b> <br>";
            }
            if (!tlcDriver.isActiveInStreetHailLivery()) {
                driverAlert += "You are not a <b> Street-Hail-Livery Active Driver. Please contact your base</b> <br>";
            }
            if (!tlcDriver.isActiveInvehiclesFhv()) {
                driverAlert += "Your vehicle is not  <b> For-Hire Vehicles FHV Active. Please contact your base</b> <br>";
            }
            if (tlcDriver.isBaseChanged()) {
                driverAlert += "Your record is no longer under our base. Please contact your base<br>";
            }
        }
    }
    String[] driverRecipients = new String[inTroubleNum];
    result.put("Driver_Alert", driverAlert);
    Email.sendEmail(result, "Driver Status Alert", new String[] { "han@cacsnyc.com" });
}

From source file:com.ecarride.App.java

public static Map<String, String> generateAdminEmailContent(Set<TlcDriver> tlcDrivers) {
    Iterator<TlcDriver> iterator = tlcDrivers.iterator();
    Map<String, String> result = new LinkedHashMap<>();
    String FhvDriverActiveResult = "<b><a href=\"https://data.cityofnewyork.us/Transportation/For-Hire-Vehicles-FHV-Active-Drivers/xjfq-wh2d/data\">These drivers are not active in For-Hire-Vehicles-FHV-Active-Drivers table</a>: "
            + "(" + (tlcDrivers.size() - fhvDriverActiveNum) + "/" + tlcDrivers.size() + ")"
            + "</b> <br><table>";
    String ShlActiveResult = "<b><a href=\"https://data.cityofnewyork.us/Transportation/Street-Hail-Livery-Drivers-Active/5tub-eh45/data\">These drivers are not active in Street-Hail-Livery-Drivers-Active table</a>: "
            + "(" + (tlcDrivers.size() - fhvShlActiveNum) + "/" + tlcDrivers.size() + ")" + "</b> <br><table>";
    String FhvVehicleResult = "<b><a href=\"https://data.cityofnewyork.us/Transportation/For-Hire-Vehicles-FHV-Active-and-Inactive-Vehicles/8wbx-tsch/data\">These drivers are not active in For-Hire-Vehicles-FHV-Active-and-Inactive-Vehicles table</a>: "
            + "(" + (tlcDrivers.size() - fhvVehichleActiveNum) + "/" + tlcDrivers.size() + ")"
            + "</b> <br><table>";
    String BaseChangedResult = "<b><a href=\"https://data.cityofnewyork.us/Transportation/For-Hire-Vehicles-FHV-Active-and-Inactive-Vehicles/8wbx-tsch/data\">These drivers are not affiliated to our base</a>: "
            + "(" + baseChangedNum + "/" + tlcDrivers.size() + ")" + "<b></br><table>";
    while (iterator.hasNext()) {
        TlcDriver driver = iterator.next();
        if (!driver.isActiveInFhvDrivers()) {
            FhvDriverActiveResult += "<tr><td><b>Name: </b><span style='padding-left:5px;'>"
                    + driver.getDriver().getFirstName() + " " + driver.getDriver().getLastName()
                    + "</span></td><td><b>TLC_FHV_License_Number: </b><span style='padding-left:5px;color:red;'>"
                    + driver.getDriver().getDriverTlcFhvLicenseNum()
                    + "  </span></td><td><b>TLC_FHV_Vehicle_License_Number: </b><span style='padding-left:5px;'>"
                    + driver.getTaxiVehicle().getVehicleTlcFhvLicenseNum() + "</span></td></tr>";
        }//from ww  w .  jav  a  2  s . co m

        if (!driver.isActiveInStreetHailLivery()) {
            ShlActiveResult += "<tr><td><b>Name: </b><span style='padding-left:5px;'>"
                    + driver.getDriver().getFirstName() + " " + driver.getDriver().getLastName()
                    + "</span></td><td><b>TLC_FHV_License_Number: </b><span style='padding-left:5px;color:red;'>"
                    + driver.getDriver().getDriverTlcFhvLicenseNum()
                    + "  </span></td><td><b>TLC_FHV_Vehicle_License_Number: </b><span style='padding-left:5px;'>"
                    + driver.getTaxiVehicle().getVehicleTlcFhvLicenseNum() + "</span></td></tr>";
        }
        if (!driver.isActiveInvehiclesFhv()) {
            FhvVehicleResult += "<tr><td><b>Name: </b><span style='padding-left:5px;'>"
                    + driver.getDriver().getFirstName() + " " + driver.getDriver().getLastName()
                    + "</span></td><td><b>TLC_FHV_License_Number: </b><span style='padding-left:5px;'>"
                    + driver.getDriver().getDriverTlcFhvLicenseNum()
                    + "  </span></td><td><b>TLC_FHV_Vehicle_License_Number: </b><span style='padding-left:5px;color:red;'>"
                    + driver.getTaxiVehicle().getVehicleTlcFhvLicenseNum() + "</span></td></tr>";
        }
        if (driver.isBaseChanged()) {
            BaseChangedResult += "<tr><td><b>Name: </b><span style='padding-left:5px;'>"
                    + driver.getDriver().getFirstName() + " " + driver.getDriver().getLastName()
                    + "</span></td><td><b>TLC_FHV_License_Number: </b><span style='padding-left:5px;'>"
                    + driver.getDriver().getDriverTlcFhvLicenseNum()
                    + "  </span></td><td><b>TLC_FHV_Vehicle_License_Number: </b><span style='padding-left:5px; color:red;'>"
                    + driver.getTaxiVehicle().getVehicleTlcFhvLicenseNum() + "</span></td></tr>";
        }
    }

    FhvDriverActiveResult += "</table>";
    ShlActiveResult += "</table>";
    FhvVehicleResult += "</table>";
    BaseChangedResult += "</table>";

    result.put("Admin_FhvDriver", FhvDriverActiveResult);
    result.put("Admin_Shl", ShlActiveResult);
    result.put("Admin_FhvVehicle", FhvVehicleResult);
    result.put("Admin_BaseChanged", BaseChangedResult);

    return result;
}

From source file:nbayes_mr.NBAYES_MR.java

public static void test(String fname) {
    try {/*  w  w  w .  ja v  a  2s  . c  o  m*/
        Scanner s = new Scanner(new File(fname));
        Double probs[] = new Double[probhmap.size()];
        int totallines = 0;
        int positive = 0;
        //System.out.println("class:"+probhmap.size());
        while (s.hasNext()) {
            totallines++;
            String line = s.nextLine();
            String split[] = line.split(",");
            Set<String> classlist = probhmap.keySet();
            Iterator classitr = classlist.iterator();
            int classi = 0;
            double maxprob = -1.0;
            String classassg = "";
            while (classitr.hasNext()) {
                String hi = (String) classitr.next();
                //System.out.println(hi);
                probs[classi] = ((double) probhmap.get(hi) / (double) total);
                for (int i = 0; i < split.length - 1; i++) {
                    int ll = 0, ll1 = 0;
                    if (probhmap.containsKey(hi)) {
                        ll = probhmap.get(hi);
                    }
                    if (probxhmap.containsKey(split[i] + "|" + hi)) {
                        ll1 = probxhmap.get(split[i] + "|" + hi);
                    }

                    //System.out.println(split[i]);

                    if (ll1 != 0) {
                        probs[classi] *= ((double) probxhmap.get(split[i] + "|" + hi)
                                / (double) probhmap.get(hi));
                    } else {
                        probs[classi] = 0.0;
                    }
                }
                if (probs[classi] > maxprob) {
                    maxprob = probs[classi];
                    classassg = hi;
                }
                classi++;
            }
            //System.out.println(line);
            //System.out.println(split.length);

            if (classassg.equalsIgnoreCase(split[10])) {
                positive++;
            }
            //s.next();
        }
        accuracy.add((double) positive / (double) totallines);
        //Integer cnt5=count/5;
        //Scanner sc = new Scanner(new File("/" + fname));

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}