Example usage for com.google.common.collect Sets newTreeSet

List of usage examples for com.google.common.collect Sets newTreeSet

Introduction

In this page you can find the example usage for com.google.common.collect Sets newTreeSet.

Prototype

public static <E> TreeSet<E> newTreeSet(Comparator<? super E> comparator) 

Source Link

Document

Creates a mutable, empty TreeSet instance with the given comparator.

Usage

From source file:org.apache.druid.segment.indexing.granularity.ArbitraryGranularitySpec.java

@JsonCreator
public ArbitraryGranularitySpec(@JsonProperty("queryGranularity") Granularity queryGranularity,
        @JsonProperty("rollup") Boolean rollup, @JsonProperty("intervals") List<Interval> inputIntervals) {
    this.queryGranularity = queryGranularity == null ? Granularities.NONE : queryGranularity;
    this.rollup = rollup == null ? Boolean.TRUE : rollup;
    this.intervals = Sets.newTreeSet(Comparators.intervalsByStartThenEnd());

    if (inputIntervals == null) {
        inputIntervals = Lists.newArrayList();
    }/* www.  j a v a 2 s  . c o m*/

    // Insert all intervals
    for (final Interval inputInterval : inputIntervals) {
        intervals.add(inputInterval);
    }

    // Ensure intervals are non-overlapping (but they may abut each other)
    final PeekingIterator<Interval> intervalIterator = Iterators.peekingIterator(intervals.iterator());
    while (intervalIterator.hasNext()) {
        final Interval currentInterval = intervalIterator.next();

        if (intervalIterator.hasNext()) {
            final Interval nextInterval = intervalIterator.peek();
            if (currentInterval.overlaps(nextInterval)) {
                throw new IAE("Overlapping intervals: %s, %s", currentInterval, nextInterval);
            }
        }
    }
}

From source file:com.textocat.textokit.postagger.opennlp.DictionaryBasedContextGenerator.java

public DictionaryBasedContextGenerator(Iterable<String> targetGramCategories, MorphDictionary morphDict) {
    this.morphDict = morphDict;
    this.gramModel = morphDict.getGramModel();
    this.tagMapper = new GramModelBasedTagMapper(gramModel);
    // re-pack into a set to avoid duplicates and maintain ID-based ordering
    TreeSet<Grammeme> tagCatGrams = Sets.newTreeSet(Grammeme.numIdComparator());
    for (String tc : targetGramCategories) {
        Grammeme tcGram = gramModel.getGrammem(tc);
        if (tcGram == null) {
            throw new IllegalArgumentException(String.format("Tag category %s does not exist", tc));
        }//from   ww  w  .  ja va  2s.  c om
        tagCatGrams.add(tcGram);
    }
    this.targetTagCategoriesMap = Maps.newHashMapWithExpectedSize(tagCatGrams.size());
    this.targetCategoriesMask = new BitSet();
    for (Grammeme tcg : tagCatGrams) {
        BitSet tcBits = gramModel.getGrammemWithChildrenBits(tcg.getId(), true);
        targetTagCategoriesMap.put(tcg, tcBits);
        targetCategoriesMask.or(tcBits);
    }
    //
    namedPredicates = AgreementPredicates.numberGenderCaseCombinations(gramModel);
}

From source file:com.edmunds.etm.rules.api.UrlRuleSet.java

/**
 * Initializes rule set from a simple collection of rules.
 *
 * @param rules the rules to use to initialized the rule set.
 *///from  www .  j av  a 2 s .c  o  m
public UrlRuleSet(Collection<UrlRule> rules) {
    this.rules = Sets.newHashSet(rules);
    this.unblockedRules = Sets.newTreeSet(AlphabeticUrlRuleComparator.INSTANCE);
    this.unblockedRules.addAll(rules);
    this.rulesBlockedByMe = Maps.newHashMap();
    this.rulesBlockingMe = Maps.newHashMap();
}

From source file:com.google.transconsole.common.messages.MessageProperties.java

/**
 * Copy constructor//from  www.  ja  v  a2  s  . co m
 */
protected MessageProperties(MessageProperties original) {
    this.contentType = original.contentType;
    this.description = original.description;
    this.name = original.name;
    this.sources = Sets.newTreeSet(original.sources);
    this.meaning = original.meaning;
    this.isHidden = original.isHidden;
    this.isObsolete = original.isObsolete;
}

From source file:com.continuuity.loom.layout.ClusterLayoutUpdater.java

public ClusterLayoutTracker addServicesToCluster(Cluster cluster, Set<Node> clusterNodes,
        Set<String> servicesToAdd) throws Exception {
    Preconditions.checkArgument(cluster != null, "Cannot add services to a nonexistant cluster.");
    Preconditions.checkArgument(clusterNodes != null && !clusterNodes.isEmpty(),
            "Cannot add services to nonexistant nodes.");

    Constraints clusterConstraints = cluster.getClusterTemplate().getConstraints();
    ClusterLayout clusterLayout = ClusterLayout.fromNodes(clusterNodes, clusterConstraints);

    Set<String> servicesToAddCopy = Sets.newHashSet(servicesToAdd);
    SortedSet<Map.Entry<String, ServiceConstraint>> sortedConstraints = Sets.newTreeSet(serviceComparator);
    sortedConstraints.addAll(clusterConstraints.getServiceConstraints().entrySet());
    Queue<String> sortedServices = Lists.newLinkedList();
    for (Map.Entry<String, ServiceConstraint> entry : sortedConstraints) {
        if (servicesToAddCopy.contains(entry.getKey())) {
            sortedServices.add(entry.getKey());
            servicesToAddCopy.remove(entry.getKey());
        }//from   w  ww . jav a 2s  . c  o m
    }
    // any service without a constraint has no limit on the number of nodes it can be placed on, so add them to the end
    sortedServices.addAll(servicesToAddCopy);

    ClusterLayoutTracker tracker = new ClusterLayoutTracker(clusterLayout);
    return canAddServicesToCluster(tracker, sortedServices) ? tracker : null;
}

From source file:controllers.GrokPatternsController.java

public Result index() {
    BreadcrumbList bc = new BreadcrumbList();
    bc.addCrumb("System", routes.SystemController.index(0));
    bc.addCrumb("Grok patterns", routes.GrokPatternsController.index());

    final Collection<GrokPatternSummary> grokPatterns;
    try {/*  ww w .j  a va  2s  . co m*/
        grokPatterns = extractorService.allGrokPatterns();
    } catch (APIException e) {
        return internalServerError();
    } catch (IOException e) {
        return internalServerError();
    }

    final TreeSet<GrokPatternSummary> sortedPatterns = Sets.newTreeSet(new Comparator<GrokPatternSummary>() {
        @Override
        public int compare(GrokPatternSummary o1, GrokPatternSummary o2) {
            return ComparisonChain.start().compare(o1.name, o2.name).result();
        }
    });
    sortedPatterns.addAll(grokPatterns);

    return ok(views.html.system.grokpatterns.index.render(currentUser(), bc, sortedPatterns));
}

From source file:com.streamsets.pipeline.lib.fuzzy.FuzzyMatch.java

public static int getRatio(String s1, String s2) {

    if (s1.length() >= s2.length()) {
        // We need to swap s1 and s2
        String temp = s2;/* www.j a  va 2s  . c om*/
        s2 = s1;
        s1 = temp;
    }

    // Get alpha numeric characters
    Set<String> set1 = tokenizeString(escapeString(s1));
    Set<String> set2 = tokenizeString(escapeString(s2));

    SetView<String> intersection = Sets.intersection(set1, set2);

    TreeSet<String> sortedIntersection = Sets.newTreeSet(intersection);

    if (LOG.isTraceEnabled()) {
        StringBuilder sortedSb = new StringBuilder();
        for (String s : sortedIntersection) {
            sortedSb.append(s).append(" ");
        }
        LOG.trace("Sorted intersection --> {}", sortedSb.toString());
    }

    // Find out difference of sets set1 and intersection of set1,set2
    SetView<String> restOfSet1 = Sets.symmetricDifference(set1, intersection);

    // Sort it
    TreeSet<String> sortedRestOfSet1 = Sets.newTreeSet(restOfSet1);

    SetView<String> restOfSet2 = Sets.symmetricDifference(set2, intersection);
    TreeSet<String> sortedRestOfSet2 = Sets.newTreeSet(restOfSet2);

    if (LOG.isTraceEnabled()) {
        StringBuilder sb1 = new StringBuilder();
        for (String s : sortedRestOfSet1) {
            sb1.append(s).append(" ");
        }
        LOG.trace("Sorted rest of 1 --> {}", sb1.toString());

        StringBuilder sb2 = new StringBuilder();
        for (String s : sortedRestOfSet1) {
            sb2.append(s).append(" ");
        }
        LOG.trace("Sorted rest of 2 --> {}", sb2.toString());
    }

    StringBuilder t0Builder = new StringBuilder("");
    StringBuilder t1Builder = new StringBuilder("");
    StringBuilder t2Builder = new StringBuilder("");

    for (String s : sortedIntersection) {
        t0Builder.append(" ").append(s);
    }
    String t0 = t0Builder.toString().trim();

    Set<String> setT1 = Sets.union(sortedIntersection, sortedRestOfSet1);
    for (String s : setT1) {
        t1Builder.append(" ").append(s);
    }
    String t1 = t1Builder.toString().trim();

    Set<String> setT2 = Sets.union(intersection, sortedRestOfSet2);
    for (String s : setT2) {
        t2Builder.append(" ").append(s);
    }

    String t2 = t2Builder.toString().trim();

    int amt1 = calculateLevenshteinDistance(t0, t1);
    int amt2 = calculateLevenshteinDistance(t0, t2);
    int amt3 = calculateLevenshteinDistance(t1, t2);

    LOG.trace("t0 = {} --> {}", t0, amt1);
    LOG.trace("t1 = {} --> {}", t1, amt2);
    LOG.trace("t2 = {} --> {}", t2, amt3);

    return Math.max(Math.max(amt1, amt2), amt3);
}

From source file:eu.interedition.collatex.medite.MediteAlgorithm.java

@Override
public void collate(VariantGraph graph, Iterable<Token> witness) {
    final VariantGraph.Vertex[][] vertices = VariantGraphRanking.of(graph).asArray();
    final Token[] tokens = Iterables.toArray(witness, Token.class);

    final SuffixTree<Token> suffixTree = SuffixTree.build(comparator, tokens);
    final MatchEvaluatorWrapper matchEvaluator = new MatchEvaluatorWrapper(this.matchEvaluator, tokens);

    final Matches matchCandidates = Matches.between(vertices, suffixTree, matchEvaluator);
    final SortedSet<SortedSet<VertexMatch.WithTokenIndex>> matches = Sets
            .newTreeSet(VertexMatch.<VertexMatch.WithTokenIndex>setComparator());

    while (true) {
        final SortedSet<SortedSet<VertexMatch.WithTokenIndex>> maximalUniqueMatches = matchCandidates
                .findMaximalUniqueMatches();
        if (maximalUniqueMatches.isEmpty()) {
            break;
        }/*from   w w w  . ja v a  2s. co  m*/

        final IntegerRangeSet rankFilter = new IntegerRangeSet();
        final IntegerRangeSet tokenFilter = new IntegerRangeSet();

        for (SortedSet<VertexMatch.WithTokenIndex> phrase : AlignmentDecisionGraph.filter(maximalUniqueMatches,
                matchEvaluator)) {
            final VertexMatch.WithTokenIndex firstMatch = phrase.first();
            final VertexMatch.WithTokenIndex lastMatch = phrase.last();

            matches.add(phrase);
            rankFilter.add(Range.closed(firstMatch.vertexRank, lastMatch.vertexRank));
            tokenFilter.add(Range.closed(firstMatch.token, lastMatch.token));
        }

        Iterables.removeIf(matchCandidates, VertexMatch.filter(rankFilter, tokenFilter));
    }

    merge(graph, vertices, tokens, matches);
}

From source file:eu.interedition.text.analysis.OverlapAnalyzer.java

@Override
public void end(long offset, Iterable<Annotation> annotations) {
    for (Annotation ending : annotations) {
        started.remove(ending);/*from  w  w  w  .  j a  v a2  s  .c om*/
    }

    for (Annotation ending : annotations) {
        final Name endingName = ending.getName();
        for (Annotation started : this.started) {
            final Name startedName = started.getName();
            if (!started.getRange().encloses(ending.getRange())) {
                if (startedName.equals(endingName)) {
                    selfOverlapping.add(endingName);
                } else {
                    overlapping.add(Sets.newTreeSet(Sets.newHashSet(startedName, endingName)));
                }
            }
        }
    }
}

From source file:com.foxelbox.foxbukkit.fun.commands.PushUpCommand.java

@Override
public void Run(Player ply, String[] args, String argStr, String commandName) throws FoxBukkitCommandException {
    args = parseFlags(args);/*w w w  .j  a v  a  2 s. c o  m*/
    final LocalSession session = plugin.worldEdit.getSession(ply);

    final double speed = Double.parseDouble(args[0]);

    final World world = ply.getWorld();

    final Region selected;
    try {
        selected = session.getSelection(BukkitUtil.getLocalWorld(world));
    } catch (IncompleteRegionException e) {
        throw new FoxBukkitCommandException("Please select a region.", e);
    }

    for (BlockVector pos : Sets.newTreeSet(selected)) {
        final int x = pos.getBlockX();
        final int y = pos.getBlockY();
        final int z = pos.getBlockZ();

        if (world.getBlockTypeIdAt(x, y, z) == 0)
            continue;

        pushUp(world, x, y, z, speed);
    }
}