Example usage for java.util HashSet add

List of usage examples for java.util HashSet add

Introduction

In this page you can find the example usage for java.util HashSet add.

Prototype

public boolean add(E e) 

Source Link

Document

Adds the specified element to this set if it is not already present.

Usage

From source file:com.ccoe.build.core.utils.FileUtils.java

public static void modifyPropertyFile(File file, Map<String, String> map) {
    List<String> postContent = new ArrayList<String>();
    try {/* ww w  .ja  v  a 2s. c  o  m*/
        List<String> originalContent = org.apache.commons.io.FileUtils.readLines(file);
        HashSet<String> keySet = new HashSet<String>();

        for (String line : originalContent) {
            if (line.trim().startsWith("#")) {
                postContent.add(line);
                continue;
            }

            String key = line.split("=")[0];
            keySet.add(key);

            if (!map.containsKey(key)) {
                postContent.add(line);
            } else {
                postContent.add(key + "=" + map.get(key));
            }
        }

        for (String key : map.keySet()) {
            if (!keySet.contains(key)) {
                postContent.add(key + "=" + map.get(key));
            }
        }

        System.out.println("keySet : " + keySet);

        org.apache.commons.io.FileUtils.writeLines(file, postContent);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:Main.java

/**
 * Read a HashSet object from an XmlPullParser. The XML data could previously
 * have been generated by writeSetXml(). The XmlPullParser must be positioned
 * <em>after</em> the tag that begins the set.
 *
 * @param parser The XmlPullParser from which to read the set data.
 * @param endTag Name of the tag that will end the set, usually "set".
 * @param name An array of one string, used to return the name attribute
 *             of the set's tag./* w  w  w .  j av a 2s.  com*/
 *
 * @return HashSet The newly generated set.
 *
 * @throws XmlPullParserException
 * @throws java.io.IOException
 *
 * @see #readSetXml
 */
public static final HashSet readThisSetXml(XmlPullParser parser, String endTag, String[] name)
        throws XmlPullParserException, java.io.IOException {
    HashSet set = new HashSet();

    int eventType = parser.getEventType();
    do {
        if (eventType == parser.START_TAG) {
            Object val = readThisValueXml(parser, name);
            set.add(val);
            //System.out.println("Adding to set: " + val);
        } else if (eventType == parser.END_TAG) {
            if (parser.getName().equals(endTag)) {
                return set;
            }
            throw new XmlPullParserException("Expected " + endTag + " end tag at: " + parser.getName());
        }
        eventType = parser.next();
    } while (eventType != parser.END_DOCUMENT);

    throw new XmlPullParserException("Document ended before " + endTag + " end tag");
}

From source file:EndmemberExtraction.java

public static void exemplarFrequency(int[] exemplarLabel, double curThresholdAbundance) {
    int[] exemplarFreq = new int[100];
    HashSet<Integer> uniqueExemplars = new HashSet<>();
    int totalExemplars = 0;
    for (int i = 0; i < exemplarLabel.length; i++) {
        if (exemplarLabel[i] != -1) {
            exemplarFreq[exemplarLabel[i]]++;
            totalExemplars++;/* w ww. j  av a 2  s .  c  o  m*/
            uniqueExemplars.add(exemplarLabel[i]);
        }
    }

    int nExemplar = uniqueExemplars.size();
    double[] fracAbundance = new double[nExemplar];
    boolean[] isRejected = new boolean[nExemplar];
    for (boolean i : isRejected) {
        i = false;
    }
    //System.out.println("nExemplar="+nExemplar);

    //System.out.println("Fractional abundance:");
    for (int i = 0; i < nExemplar; i++) {
        fracAbundance[i] = (double) exemplarFreq[i] / totalExemplars;

        if (fracAbundance[i] < curThresholdAbundance) {
            isRejected[i] = true;
        }
        //System.out.println(i+" : "+(fracAbundance[i]*100));
    }
    //System.out.println();
    int count = 0;
    for (int i = 0; i < exemplarLabel.length; i++) {
        if (exemplarLabel[i] != -1) {
            if (isRejected[exemplarLabel[i]]) {
                exemplarLabel[i] = -1;
            }
        }
    }
}

From source file:mailbox.CreationViaEmail.java

private static void addEvent(NotificationEvent event, Address[] recipients, User sender) {
    HashSet<User> emailUsers = new HashSet<>();
    emailUsers.add(sender);
    for (Address addr : recipients) {
        emailUsers.add(User.findByEmail(((InternetAddress) addr).getAddress()));
    }/*from  w  w w .  j  a va2  s.co m*/
    event.receivers.removeAll(emailUsers);
    NotificationEvent.add(event);
}

From source file:Main.java

/**
 *
 * @param input map to reverse//from ww w .  j  a  va  2  s  .c  o m
 * @param <T> type of map and collection
 * @return reversed map with value sets switched with key sets.
 */
public static <T> Map<T, HashSet<T>> reverseMap(Map<T, ? extends Collection<T>> input) {

    Map<T, HashSet<T>> ret = new HashMap<T, HashSet<T>>();

    for (Map.Entry<T, ? extends Collection<T>> entry : input.entrySet()) {

        final Collection<T> values = entry.getValue();
        final T key = entry.getKey();

        //foreach value in key->values mapping
        for (T value : values) {

            //get the reversed collection created when previously iterated keys
            // were associated with this value, value -> keys
            HashSet<T> newValues = ret.get(value);

            //if we've never processed a key that pointed to this value -
            // it's time to initialize the reversed collection from this value to keys that pointed to it
            if (newValues == null) {

                newValues = new HashSet<T>();
                ret.put(value, newValues);
            }

            //and obviously put the key in the reversed collection
            newValues.add(key);
        }
    }

    return ret;
}

From source file:at.treedb.util.SevenZip.java

/**
 * Extracts some data (files and directories) from the archive without
 * extracting the whole archive.//from  w  ww  .j  a  va 2  s .co  m
 * 
 * @param archive
 *            7-zip archive
 * @param fileList
 *            file extraction list, a path with an ending '/' denotes a
 *            directory
 * @return file list as a map file name/file data
 * @throws IOException
 */
public static HashMap<String, byte[]> exctact(File archive, String... fileList) throws IOException {
    HashSet<String> fileSet = new HashSet<String>();
    ArrayList<String> dirList = new ArrayList<String>();
    for (String f : fileList) {
        if (!f.endsWith("/")) {
            fileSet.add(f);
        } else {
            dirList.add(f);
        }
    }
    HashMap<String, byte[]> resultMap = new HashMap<String, byte[]>();
    SevenZFile sevenZFile = new SevenZFile(archive);
    do {
        SevenZArchiveEntry entry = sevenZFile.getNextEntry();
        if (entry == null) {
            break;
        }
        // convert window path to unix style
        String name = entry.getName().replace('\\', '/');
        if (!entry.isDirectory()) {
            boolean storeFile = false;
            if (fileSet.contains(name)) {
                storeFile = true;
            } else {
                // search directories
                for (String s : dirList) {
                    if (name.startsWith(s)) {
                        storeFile = true;
                        break;
                    }
                }
            }
            // store the file
            if (storeFile) {
                int size = (int) entry.getSize();
                byte[] data = new byte[size];
                sevenZFile.read(data, 0, size);
                resultMap.put(name, data);
                // in this case we can finish the extraction loop
                if (dirList.isEmpty() && resultMap.size() == fileSet.size()) {
                    break;
                }
            }
        }
    } while (true);
    sevenZFile.close();
    return resultMap;
}

From source file:com.dtolabs.rundeck.ec2.NodeGenerator.java

public static INodeEntry instanceToNode(final Instance inst, final Properties mapping)
        throws GeneratorException {
    String hostSel = mapping.getProperty("hostname.selector");
    String host = applySelector(inst, hostSel, mapping.getProperty("hostname.default"));
    if (null == host) {
        System.err.println("Unable to determine hostname for instance: " + inst.getInstanceId());
        return null;
    }//from  w  ww. jav a  2s  .  c  om
    String nameSel = mapping.getProperty("name.selector");
    String name = applySelector(inst, nameSel, mapping.getProperty("name.default"));
    if (null == name) {
        name = host;
    }
    NodeEntryImpl node = new NodeEntryImpl(host, name);
    String descSel = mapping.getProperty("description.selector");
    String desc = applySelector(inst, descSel, mapping.getProperty("description.default"));
    node.setDescription(desc);

    for (final String prop : ResourceXMLConstants.nodeProps) {
        final String value = applySelector(inst, mapping.getProperty(prop + ".selector"),
                mapping.getProperty(prop + ".default"));
        if (null != value) {
            try {
                BeanUtils.setProperty(node, prop, value);
            } catch (Exception e) {
                throw new GeneratorException(e);
            }
        }
    }
    String[] attrProps = new String[] { ResourceXMLConstants.NODE_REMOTE_URL,
            ResourceXMLConstants.NODE_EDIT_URL };
    for (final String attrProp : attrProps) {
        final String value = applySelector(inst, mapping.getProperty(attrProp + ".selector"),
                mapping.getProperty(attrProp + ".default"));
        if (null != value) {
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            node.getAttributes().put(attrProp, value);
        }
    }

    Pattern settingPat = Pattern.compile("^setting\\.(.+?)\\.selector$");
    //evaluate setting selectors
    for (final Object o : mapping.keySet()) {
        String key = (String) o;
        String selector = mapping.getProperty(key);
        Matcher m = settingPat.matcher(key);
        if (m.matches()) {
            String setName = m.group(1);
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            final String value = applySelector(inst, selector,
                    mapping.getProperty("setting." + setName + ".default"));
            if (null != value) {
                //use nodename-settingname to make the setting unique to the node
                node.getAttributes().put(setName, value);
            }
        }
    }
    //evaluate single settings.selector=tags/* mapping
    if ("tags/*".equals(mapping.getProperty("settings.selector"))) {
        //iterate through instance tags and generate settings
        for (final Tag tag : inst.getTags()) {
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            node.getAttributes().put(tag.getKey(), tag.getValue());
        }
    }
    //evaluate single settings.selector=tags/* mapping
    if ("tags/*".equals(mapping.getProperty("attributes.selector"))) {
        //iterate through instance tags and generate settings
        for (final Tag tag : inst.getTags()) {
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            node.getAttributes().put(tag.getKey(), tag.getValue());
        }
    }
    if (null != mapping.getProperty("tags.selector")) {
        final String selector = mapping.getProperty("tags.selector");
        final String value = applySelector(inst, selector, mapping.getProperty("tags.default"));
        if (null != value) {
            final String[] values = value.split(",");
            final HashSet<String> tagset = new HashSet<String>();
            for (final String s : values) {
                tagset.add(s.trim());
            }
            if (null == node.getTags()) {
                node.setTags(tagset);
            } else {
                node.getTags().addAll(tagset);
            }
        }
    }

    //apply specific tag selectors
    Pattern tagPat = Pattern.compile("^tag\\.(.+?)\\.selector$");
    //evaluate tag selectors
    for (final Object o : mapping.keySet()) {
        String key = (String) o;
        String selector = mapping.getProperty(key);
        //split selector by = if present
        String[] selparts = selector.split("=");
        Matcher m = tagPat.matcher(key);
        if (m.matches()) {
            String tagName = m.group(1);
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            final String value = applySelector(inst, selparts[0], null);
            if (null != value) {
                if (selparts.length > 1 && !value.equals(selparts[1])) {
                    continue;
                }
                //use add the tag if the value is not null
                if (null == node.getTags()) {
                    node.setTags(new HashSet());
                }
                node.getTags().add(tagName);
            }
        }
    }

    //apply attribute selectors

    Pattern attribPat = Pattern.compile("^attribute\\.(.+?)\\.selector$");
    //evaluate setting selectors
    for (final Object o : mapping.keySet()) {
        String key = (String) o;
        String selector = mapping.getProperty(key);
        Matcher m = attribPat.matcher(key);
        if (m.matches()) {
            String attrName = m.group(1);
            if (null == node.getAttributes()) {
                node.setAttributes(new HashMap<String, String>());
            }
            final String value = applySelector(inst, selector,
                    mapping.getProperty("attribute." + attrName + ".default"));
            if (null != value) {
                //use nodename-settingname to make the setting unique to the node
                node.getAttributes().put(attrName, value);
            }
        }
    }
    return node;
}

From source file:ca.sfu.federation.utils.IContextUtils.java

public static Map<String, INamed> getDependancies(Map<String, INamed> ElementMap) {
    // init/*from  www  . j  a va 2 s  .co  m*/
    LinkedHashMap<String, INamed> results = new LinkedHashMap<String, INamed>();
    HashSet dependancies = new HashSet();
    // scenario dependancies come from contextual object references
    Iterator iter = ElementMap.values().iterator();
    while (iter.hasNext()) {
        INamed named = (INamed) iter.next();
        dependancies.add(named.getContext());
    }
    // convert set to map
    iter = dependancies.iterator();
    while (iter.hasNext()) {
        INamed named = (INamed) iter.next();
        results.put(named.getName(), named);
    }
    // return result
    return results;
}

From source file:com.sec.ose.osi.sdk.protexsdk.discovery.ReportAPIWrapper.java

protected static void discardAllDataForProject(String pProjectName) {
    log.debug("refresh() - " + pProjectName);

    HashSet<String> removeKeySet = new HashSet<String>();
    String removeKeyword = pProjectName + SEPERATOR;

    for (String curKey : mReportTable.keySet()) {

        if (curKey.startsWith(removeKeyword)) {
            removeKeySet.add(curKey);
        }//  w w w .  j  av  a  2s .co m
    }

    for (String removeKey : removeKeySet) {
        log.debug("discardData: " + removeKey);
        mReportTable.remove(removeKey);
    }

    System.gc();
}

From source file:com.sencko.basketball.stats.advanced.FIBAJsonParser.java

static void analyzeGame(Game game) {
    HashSet[] playersInGameTeam = { new HashSet<String>(5), new HashSet<String>(5) };
    HashSet[] playersInRest = { new HashSet<String>(5), new HashSet<String>(5) };
    HashMap[][] plusMinusPlayers = { { new HashMap<String, Integer>(), new HashMap<String, Integer>() },
            { new HashMap<String, Integer>(), new HashMap<String, Integer>() } };
    for (int i = game.getPbp().size() - 1; i >= 0; i--) {
        Event event = game.getPbp().get(i);
        if (EventType.sub.equals(event.getTyp())) {
            HashSet<String> teamSet = playersInGameTeam[event.getTno() - 1];
            HashSet<String> restSet = playersInRest[event.getTno() - 1];
            String actor = event.getActor().toString();
            if (teamSet.contains(actor)) {
                teamSet.remove(actor);//from  w ww .ja  v  a  2s  .co  m
                restSet.add(actor);
            } else {
                teamSet.add(actor);
                if (restSet.contains(actor)) {
                    restSet.remove(actor);
                } else {
                    //add plus minus on bench
                    HashMap<String, Integer> bench = plusMinusPlayers[event.getTno() - 1][1];
                    int change = (event.getTno() == 1) ? (event.getS1() - event.getS2())
                            : (event.getS2() - event.getS1());
                    bench.put(actor, change);
                }
            }

            //   System.out.println(Arrays.toString(playersInGameTeam));
        } else if (i != game.getPbp().size() - 1) {
            Event previousEvent = game.getPbp().get(i + 1);
            int change = 0;
            if (previousEvent.getS1() != event.getS1()) {
                change += event.getS1() - previousEvent.getS1();
            }
            if (previousEvent.getS2() != event.getS2()) {
                change -= event.getS2() - previousEvent.getS2();
            }
            for (int j = 0; j < 2; j++) {
                HashSet<String> teamSet = playersInGameTeam[j];
                for (String player : teamSet) {
                    HashMap<String, Integer> prev = plusMinusPlayers[j][0];
                    Integer previous = prev.get(player);
                    if (previous == null) {
                        previous = 0;
                    }
                    previous = previous + change;
                    prev.put(player, previous);
                }

                HashSet<String> restSet = playersInRest[j];
                for (String player : restSet) {
                    HashMap<String, Integer> prev = plusMinusPlayers[j][1];
                    Integer previous = prev.get(player);
                    if (previous == null) {
                        previous = 0;
                    }
                    previous = previous + change;
                    prev.put(player, previous);
                }

                change = -change;
            }
        }
    }
    //     System.out.println(Arrays.deepToString(plusMinusPlayers));

    for (int i = 0; i < 2; i++) {
        HashMap<String, Integer> board = plusMinusPlayers[i][0];
        HashMap<String, Integer> bench = plusMinusPlayers[i][1];
        int checkSum = 0;
        for (String name : board.keySet()) {
            int plusS = board.get(name);
            int plusB = bench.get(name);
            int total = plusS - plusB;
            System.out.printf("%20s\t%4d\t%4d\t%4d\n", name, plusS, plusB, total);
            checkSum += total;
        }

        System.out.println(checkSum + "----------------------------------------");
    }
}