Example usage for java.util TreeSet add

List of usage examples for java.util TreeSet add

Introduction

In this page you can find the example usage for java.util TreeSet 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:de.knowwe.visualization.util.Utils.java

public static String prepareLabel(String string) {
    // if (true) return string;
    String lb = LINE_BREAK;/*ww  w.  j  ava  2  s  .  co m*/

    int length = string.length();
    if (length < 13)
        return clean(string, lb);

    // find possible line break positions
    Set<Integer> possibleLBs = new TreeSet<>();

    // possible line breaks are before the following chars:
    // _ >= <= = . ( [ and white spaces
    Matcher m = Pattern.compile("_|>=|<=|=|\\.|\\([^\\)]{1}|\\[[^\\]]{1}").matcher(string);
    while (m.find()) {
        possibleLBs.add(m.start(0));
    }
    // line breaks at whitespace only if they are not in range of = or > or
    // <
    m = Pattern.compile("(?<=[^=<>]){3}( )(?=[^=<>]{3})").matcher(string);
    while (m.find()) {
        possibleLBs.add(m.start(1));
    }

    if (possibleLBs.isEmpty())
        return clean(string, lb);

    // add the line breaks were it makes sense
    List<Integer> desiredLBs = new LinkedList<>();
    Set<Integer> addedLBs = new TreeSet<>();

    // optimal length is determined by the length of the given String
    double optimalLength = (double) length / Math.sqrt(length / 5);

    for (int i = 1; i < string.length() / optimalLength; i++) {
        // having the line breaks on these position would be optimal
        desiredLBs.add((int) Math.round(i * optimalLength));
    }

    //todo: remove creation of trailing linebreaks

    // try to find those possible line breaks that closest to the optimal
    // line breaks
    int d = 0;
    for (Integer desLB : desiredLBs) {
        int bestCandiadate = 0;
        // to avoid breaks for only a few chars at the end, we make
        // extra efforts for the last line break
        // we get the line break that produces the smallest variance
        // we should actually calculate the best break via variance for
        // all line breaks, but that seems rather complex and not yet
        // justified right now, since the current simple algorithm
        // already produces nice results
        if (d == desiredLBs.size() - 1) {
            double bestVar = Double.MAX_VALUE;
            for (Integer posLB : possibleLBs) {
                Set<Integer> temp = new TreeSet<>(addedLBs);
                temp.add(posLB);
                TreeSet<Integer> varianceCheck = new TreeSet<>(temp);
                varianceCheck.add(length);
                double variance = getVariance(varianceCheck);
                if (variance <= bestVar) {
                    bestVar = variance;
                    bestCandiadate = posLB;
                }
            }
        }
        // for all other breakpoints, just get the one closest to the
        // desired position
        else {
            for (Integer posLB : possibleLBs) {
                if (Math.abs(desLB - posLB) <= Math.abs(desLB - bestCandiadate)) {
                    bestCandiadate = posLB;
                }
            }
        }
        if (bestCandiadate != 0 && bestCandiadate != length) {
            addedLBs.add(bestCandiadate);
        }
        d++;
    }

    // but in the line breaks
    StringBuilder labelBuilder = new StringBuilder();
    List<String> split = new ArrayList<>(addedLBs.size() + 1);
    int last = 0;
    for (Integer addedLB : addedLBs) {
        split.add(string.substring(last, addedLB));
        last = addedLB;
    }
    split.add(string.substring(last, string.length()));
    for (String s : split) {
        // clean the substrings
        labelBuilder.append(clean(s.trim(), lb)).append(lb);
    }

    String label = labelBuilder.toString();
    return label;
}

From source file:com.ettoremastrogiacomo.sktradingjava.starters.Temp.java

public static java.util.ArrayList<TreeSet<UDate>> timesegments(java.util.TreeSet<UDate> dates,
        long maxgapmsec) {
    java.util.TreeMap<Integer, TreeSet<UDate>> rank = new java.util.TreeMap<>();
    java.util.TreeSet<UDate> t = new TreeSet<>();
    java.util.ArrayList<TreeSet<UDate>> list = new ArrayList<>();
    for (UDate d : dates) {
        if (t.isEmpty()) {
            t.add(d);
        } else if (d.diffmills(t.last()) > maxgapmsec) {
            rank.put(t.size(), t);//from  w ww. j  a  v a 2s.co m
            list.add(t);
            t = new TreeSet<>();
        } else {
            t.add(d);
        }
    }

    return list;
}

From source file:net.algart.simagis.live.json.minimal.SimagisLiveUtils.java

public static Set<String> getKeySet(JSONObject jsonObject) {
    if (jsonObject == null) {
        return Collections.emptySet();
    }/*from w w w . j a v  a  2  s  . c o m*/
    final TreeSet<String> result = new TreeSet<String>();
    final Iterator keys = jsonObject.keys();
    while (keys.hasNext()) {
        result.add((String) keys.next());
    }
    return Collections.unmodifiableSortedSet(result);
}

From source file:gemlite.core.internal.admin.AdminUtil.java

/**
 * ?memberIds/*from  w w  w  . j a  va2s.  c  o  m*/
 * @param cache
 * @return
 */
public static Set getAllMemberIds(Cache cache) {
    TreeSet<String> set = new TreeSet<String>();
    Set<DistributedMember> memberSet = new HashSet(((InternalDistributedSystem) cache.getDistributedSystem())
            .getDistributionManager().getDistributionManagerIds());
    for (DistributedMember member : memberSet) {
        set.add(member.getId());
    }
    return set;
}

From source file:cf.adriantodt.utils.HTML2Discord.java

public static String toPlainText(String discordFormatMessage) {
    String strippedContent;/*  w  ww . ja v a 2 s.  c om*/
    //all the formatting keys to keep track of
    String[] keys = new String[] { "*", "_", "`", "~~" };

    //find all tokens (formatting strings described above)
    TreeSet<FormatToken> tokens = new TreeSet<>((t1, t2) -> Integer.compare(t1.start, t2.start));
    for (String key : keys) {
        Matcher matcher = Pattern.compile(Pattern.quote(key)).matcher(discordFormatMessage);
        while (matcher.find()) {
            tokens.add(new FormatToken(key, matcher.start()));
        }
    }

    //iterate over all tokens, find all matching pairs, and add them to the list toRemove
    Stack<FormatToken> stack = new Stack<>();
    List<FormatToken> toRemove = new ArrayList<>();
    boolean inBlock = false;
    for (FormatToken token : tokens) {
        if (stack.empty() || !stack.peek().format.equals(token.format)
                || stack.peek().start + token.format.length() == token.start) {
            //we are at opening tag
            if (!inBlock) {
                //we are outside of block -> handle normally
                if (token.format.equals("`")) {
                    //block start... invalidate all previous tags
                    stack.clear();
                    inBlock = true;
                }
                stack.push(token);
            } else if (token.format.equals("`")) {
                //we are inside of a block -> handle only block tag
                stack.push(token);
            }
        } else if (!stack.empty()) {
            //we found a matching close-tag
            toRemove.add(stack.pop());
            toRemove.add(token);
            if (token.format.equals("`") && stack.empty()) {
                //close tag closed the block
                inBlock = false;
            }
        }
    }

    //sort tags to remove by their start-index and iteratively build the remaining string
    Collections.sort(toRemove, (t1, t2) -> Integer.compare(t1.start, t2.start));
    StringBuilder out = new StringBuilder();
    int currIndex = 0;
    for (FormatToken formatToken : toRemove) {
        if (currIndex < formatToken.start) {
            out.append(discordFormatMessage.substring(currIndex, formatToken.start));
        }
        currIndex = formatToken.start + formatToken.format.length();
    }
    if (currIndex < discordFormatMessage.length()) {
        out.append(discordFormatMessage.substring(currIndex));
    }
    //return the stripped text, escape all remaining formatting characters (did not have matching open/close before or were left/right of block
    strippedContent = out.toString().replace("*", "\\*").replace("_", "\\_").replace("~", "\\~");
    return strippedContent;
}

From source file:base.Engine.java

static Set<TreeSet<PatternInstance>> addPair(Set<TreeSet<PatternInstance>> returnSet, PatternInstance p1,
        PatternInstance p2) {/*from  www  . ja v  a  2s.  c o  m*/
    TreeSet<PatternInstance> t1 = null;
    TreeSet<PatternInstance> t2 = null;
    for (TreeSet<PatternInstance> aTree : returnSet) {
        if (aTree.contains(p1)) {
            t1 = aTree;
            break;
        }
    }
    for (TreeSet<PatternInstance> aTree : returnSet) {
        if (aTree.contains(p2)) {
            t2 = aTree;
            break;
        }
    }

    if (t1 == null && t2 == null) {
        TreeSet<PatternInstance> newTree = new TreeSet<>(new InstanceComparator());
        newTree.add(p1);
        newTree.add(p2);
        returnSet.add(newTree);
    } else if (t1 == null && t2 != null) {
        t2.add(p1);
    } else if (t1 != null && t2 == null) {
        t1.add(p2);
    } else if (t1 != t2) {
        t1.addAll(t2);
        returnSet.remove(t2);
    }
    return returnSet;
}

From source file:ch.entwine.weblounge.common.url.UrlUtils.java

/**
 * Sorts the given urls by path./*from w  w  w  .  ja va  2s  .c om*/
 * 
 * @param urls
 *          the urls to sort
 * @return the sorted urls
 */
public static String[] sort(String[] urls) {
    TreeSet<String> set = new TreeSet<String>();
    for (int i = 0; i < urls.length; i++)
        set.add(urls[i]);
    String[] result = new String[urls.length];
    Iterator<String> i = set.iterator();
    int index = 0;
    while (i.hasNext()) {
        result[index++] = i.toString();
    }
    return result;
}

From source file:ai.susi.json.JsonRepository.java

private static SortedSet<File> tailSet(SortedSet<File> set, int count) {
    if (count >= set.size())
        return set;
    TreeSet<File> t = new TreeSet<File>();
    Iterator<File> fi = set.iterator();
    for (int i = 0; i < set.size() - count; i++)
        fi.next();/*from   w w  w. j a va  2 s .com*/
    while (fi.hasNext())
        t.add(fi.next());
    return t;
}

From source file:com.espertech.esper.event.vaevent.PropertyUtility.java

private static MultiKey<String> getPropertiesContributed(EventType deltaEventType,
        String[] allPropertiesSorted) {

    TreeSet<String> props = new TreeSet<String>();
    for (String property : deltaEventType.getPropertyNames()) {
        for (String propInAll : allPropertiesSorted) {
            if (propInAll.equals(property)) {
                props.add(property);
                break;
            }//from   w  w w.j av a 2 s  .  co  m
        }
    }
    return new MultiKey<String>(props.toArray(new String[props.size()]));
}

From source file:juicebox.data.HiCFileTools.java

/**
 * Given an array of possible resolutions, returns the actual resolutions available in the dataset
 *
 * @param ds//from  w w  w. j a v  a 2  s  .c o  m
 * @param resolutions
 * @return finalResolutions Set
 */
public static List<Integer> filterResolutions(Dataset ds, int[] resolutions) {

    TreeSet<Integer> resSet = new TreeSet<Integer>();
    for (HiCZoom zoom : ds.getBpZooms()) {
        resSet.add(zoom.getBinSize());
    }

    List<Integer> finalResolutions = new ArrayList<Integer>();
    for (int res : resolutions) {
        finalResolutions.add(closestValue(res, resSet));
    }

    return finalResolutions;
}