com.google.common.collect.Ordering Java Examples

The following examples show how to use com.google.common.collect.Ordering. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SdkMavenRepository.java    From bazel with Apache License 2.0 7 votes vote down vote up
/**
 * Parses a set of maven repository directory trees looking for and parsing .pom files.
 */
static SdkMavenRepository create(Iterable<Path> mavenRepositories) throws IOException {
  Collection<Path> pomPaths = new ArrayList<>();
  for (Path mavenRepository : mavenRepositories) {
    pomPaths.addAll(
        FileSystemUtils.traverseTree(mavenRepository, path -> path.toString().endsWith(".pom")));
  }

  ImmutableSortedSet.Builder<Pom> poms =
      new ImmutableSortedSet.Builder<>(Ordering.usingToString());
  for (Path pomPath : pomPaths) {
    try {
      Pom pom = Pom.parse(pomPath);
      if (pom != null) {
        poms.add(pom);
      }
    } catch (ParserConfigurationException | SAXException e) {
      throw new IOException(e);
    }
  }
  return new SdkMavenRepository(poms.build());
}
 
Example #2
Source File: FakeStructApi.java    From bazel with Apache License 2.0 6 votes vote down vote up
/** Converts the object to string using Starlark syntax. */
@Override
public void repr(Printer printer) {
  boolean first = true;
  printer.append("struct(");
  for (String fieldName : Ordering.natural().sortedCopy(getFieldNames())) {
    if (!first) {
      printer.append(", ");
    }
    first = false;
    printer.append(fieldName);
    printer.append(" = ");
    printer.repr(getValueOrNull(fieldName));
  }

  printer.append(")");
}
 
Example #3
Source File: GherkinCheckVerifier.java    From sonar-gherkin-plugin with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static List<Integer> secondary(Issue issue) {
  List<Integer> result = new ArrayList<>();

  if (issue instanceof PreciseIssue) {
    result.addAll(((PreciseIssue) issue).secondaryLocations()
      .stream()
      .map(IssueLocation::startLine)
      .collect(Collectors.toList()));
  } else if (issue instanceof FileIssue) {
    result.addAll(((FileIssue) issue).secondaryLocations()
      .stream()
      .map(IssueLocation::startLine)
      .collect(Collectors.toList()));
  }
  return Ordering.natural().sortedCopy(result);
}
 
Example #4
Source File: FeatureKnnModel.java    From samantha with MIT License 6 votes vote down vote up
private List<double[]> getNeighbors(int curIndex, IntList svdIndices,
                                    SVDFeature svdFeature,
                                    List<String> features) {
    List<double[]> raw = new ArrayList<>(svdIndices.size());
    for (int target : svdIndices) {
        if (target != curIndex && (numMatch == 0 || matchPrefixFeatures(curIndex, target, features))) {
            double[] pair = new double[2];
            pair[0] = target;
            pair[1] = svdFeature.getVectorVarByNameIndex(SVDFeatureKey.FACTORS.get(), target)
                    .cosine(svdFeature.getVectorVarByNameIndex(SVDFeatureKey.FACTORS.get(), curIndex));
            raw.add(pair);
        }
    }
    Ordering<double[]> pairDoubleOrdering = SortingUtilities.pairDoubleSecondOrdering();
    List<double[]> neighbors;
    if (reverse) {
        neighbors = pairDoubleOrdering.leastOf(raw, numNeighbors);
    } else {
        neighbors = pairDoubleOrdering.greatestOf(raw, numNeighbors);
    }
    return neighbors;
}
 
Example #5
Source File: DatatypeDate.java    From metanome-algorithms with Apache License 2.0 6 votes vote down vote up
public DatatypeDate(final Comparator<Date> comparator, final String dateFormat) {
  this.specificType = type.DATE;
  this.setDateFormat(dateFormat);

  if (comparator == null) {
    this.indexedComparator = new Comparator<RowIndexedDateValue>() {

      @Override
      public int compare(final RowIndexedDateValue o1, final RowIndexedDateValue o2) {
        return ComparisonChain.start()
            .compare(o1.value, o2.value, Ordering.natural().nullsFirst()).result();
      }

    };
  } else {
    this.indexedComparator = new Comparator<RowIndexedDateValue>() {

      @Override
      public int compare(final RowIndexedDateValue o1, final RowIndexedDateValue o2) {
        return ComparisonChain.start()
            .compare(o1.value, o2.value, Ordering.from(comparator).nullsFirst()).result();
      }

    };
  }
}
 
Example #6
Source File: Counter.java    From java-monitoring-client-library with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
final ImmutableList<MetricPoint<Long>> getTimestampedValues(Instant endTimestamp) {
  ImmutableList.Builder<MetricPoint<Long>> timestampedValues = new ImmutableList.Builder<>();
  for (Entry<ImmutableList<String>, Long> entry : values.asMap().entrySet()) {
    ImmutableList<String> labelValues = entry.getKey();
    valueLocks.get(labelValues).lock();

    Instant startTimestamp;
    try {
      startTimestamp = valueStartTimestamps.get(labelValues);
    } finally {
      valueLocks.get(labelValues).unlock();
    }

    // There is an opportunity for endTimestamp to be less than startTimestamp if
    // one of the modification methods is called on a value before the lock for that value is
    // acquired but after getTimestampedValues has been invoked. Just set endTimestamp equal to
    // startTimestamp if that happens.
    endTimestamp = Ordering.natural().max(startTimestamp, endTimestamp);

    timestampedValues.add(
        MetricPoint.create(this, labelValues, startTimestamp, endTimestamp, entry.getValue()));
  }
  return timestampedValues.build();
}
 
Example #7
Source File: TaskRepository.java    From estatio with Apache License 2.0 6 votes vote down vote up
/**
 * Incomplete, assigned explicitly to me, AND ALSO any tasks not assigned to anyone but for which
 * I have the (party) roles to perform them (so should be part of "my tasks") before {@param createdOn}
 * @param createdOn
 * @return
 */
@Programmatic
public List<Task> findIncompleteForMeAndCreatedOnBefore(final LocalDateTime createdOn){
    final Person meAsPerson = meAsPerson();
    if(meAsPerson == null) {
        return Lists.newArrayList();
    }

    final List<Task> tasks = findIncompleteForAndCreatedOnBefore(meAsPerson, createdOn);
    final List<Task> myRolesTasksUnassigned = findIncompleteForMyRolesAndUnassignedAndCreatedOnBefore(createdOn);
    tasks.addAll(myRolesTasksUnassigned);
    Comparator<Task> comparator = Comparator.comparing(Task::getPriority, Ordering.natural().nullsLast())
            .thenComparing(Task::getCreatedOn, Ordering.natural().nullsLast().reverse());
    tasks.sort(comparator);
    return tasks;
}
 
Example #8
Source File: OpenTypeSelectionDialog.java    From n4js with Eclipse Public License 1.0 6 votes vote down vote up
@Override
@SuppressWarnings({ "rawtypes", "unchecked", "static-access" })
protected Comparator getItemsComparator() {
	return Ordering.natural().nullsLast().from(new Comparator() {

		@Override
		public int compare(final Object o1, final Object o2) {
			if (o1 instanceof IEObjectDescription && o2 instanceof IEObjectDescription) {
				final IEObjectDescription d1 = (IEObjectDescription) o1;
				final IEObjectDescription d2 = (IEObjectDescription) o2;
				final QualifiedName fqn1 = d1.getQualifiedName();
				final QualifiedName fqn2 = d2.getQualifiedName();
				if (null != fqn1 && null != fqn2) {
					return nullToEmpty(fqn1.getLastSegment()).compareToIgnoreCase(
							nullToEmpty(fqn2.getLastSegment()));
				}
			}
			return Objects.hashCode(o1) - Objects.hashCode(o2);
		}
	});
}
 
Example #9
Source File: QueryHelper.java    From incubator-retired-wave with Apache License 2.0 6 votes vote down vote up
/**
 * Computes ordering for the search results. If none are specified - then
 * returns the default ordering. The resulting ordering is always compounded
 * with ordering by wave id for stability.
 */
public static Ordering<WaveViewData> computeSorter(
    Map<TokenQueryType, Set<String>> queryParams) {
  Ordering<WaveViewData> ordering = null;
  Set<String> orderBySet = queryParams.get(TokenQueryType.ORDERBY);
  if (orderBySet != null) {
    for (String orderBy : orderBySet) {
      QueryHelper.OrderByValueType orderingType =
          QueryHelper.OrderByValueType.fromToken(orderBy);
      if (ordering == null) {
        // Primary ordering.
        ordering = orderingType.getOrdering();
      } else {
        // All other ordering are compounded to the primary one.
        ordering = ordering.compound(orderingType.getOrdering());
      }
    }
  } else {
    ordering = QueryHelper.DEFAULT_ORDERING;
  }
  // For stability order also by wave id.
  ordering = ordering.compound(QueryHelper.ID_COMPARATOR);
  return ordering;
}
 
Example #10
Source File: DomainCheckFlowTest.java    From nomulus with Apache License 2.0 6 votes vote down vote up
@Test
public void testFeeExtension_premium_eap_v06_withRenewalOnRestore() throws Exception {
  createTld("example");
  setEppInput("domain_check_fee_premium_v06.xml");
  clock.setTo(DateTime.parse("2010-01-01T10:00:00Z"));
  persistPendingDeleteDomain("rich.example");
  persistResource(
      Registry.get("example")
          .asBuilder()
          .setEapFeeSchedule(
              new ImmutableSortedMap.Builder<DateTime, Money>(Ordering.natural())
                  .put(START_OF_TIME, Money.of(USD, 0))
                  .put(clock.nowUtc().minusDays(1), Money.of(USD, 100))
                  .put(clock.nowUtc().plusDays(1), Money.of(USD, 50))
                  .put(clock.nowUtc().plusDays(2), Money.of(USD, 0))
                  .build())
          .build());

  runFlowAssertResponse(loadFile("domain_check_fee_premium_eap_response_v06_with_renewal.xml"));
}
 
Example #11
Source File: QueryShuffleTransformation.java    From trainbenchmark with Eclipse Public License 1.0 6 votes vote down vote up
public List<TPatternMatch> shuffle(int nMatchesToModify) throws Exception {
	final Ordering<? super TPatternMatch> ordering = Ordering.from(comparator);

	// some tools, e.g. Neo4j require to be in a transaction to get properties
	// (used to get the ID properties for ordering)
	driver.beginTransaction();
	sortedMatches = ordering.sortedCopy(matches);
	driver.finishTransaction();

	final int size = sortedMatches.size();
	if (size < nMatchesToModify) {
		nMatchesToModify = size;
	}
	Collections.shuffle(sortedMatches, random);
	candidates = new ArrayList<>(nMatchesToModify);
	for (int i = 0; i < nMatchesToModify; i++) {
		final TPatternMatch candidate = sortedMatches.get(i);
		candidates.add(candidate);
	}

	return candidates;
}
 
Example #12
Source File: TimedTransitionProperty.java    From nomulus with Apache License 2.0 6 votes vote down vote up
/**
 * Converts the provided value map into the equivalent transition map, using transition objects
 * of the given TimedTransition subclass.  The value map must be sorted according to the natural
 * ordering of its DateTime keys, and keys cannot be earlier than START_OF_TIME.
 */
// NB: The Class<T> parameter could be eliminated by getting the class via reflection, but then
// the callsite cannot infer T, so unless you explicitly call this as .<V, T>fromValueMap() it
// will default to using just TimedTransition<V>, which fails at runtime.
private static <V, T extends TimedTransition<V>> NavigableMap<DateTime, T> makeTransitionMap(
    ImmutableSortedMap<DateTime, V> valueMap,
    final Class<T> timedTransitionSubclass) {
  checkArgument(
      Ordering.natural().equals(valueMap.comparator()),
      "Timed transition value map must have transition time keys in chronological order");
  return Maps.transformEntries(
      valueMap,
      (DateTime transitionTime, V value) -> {
        checkArgument(
            !transitionTime.isBefore(START_OF_TIME),
            "Timed transition times cannot be earlier than START_OF_TIME / Unix Epoch");
        T subclass = TypeUtils.instantiate(timedTransitionSubclass);
        ((TimedTransition<V>) subclass).transitionTime = transitionTime;
        subclass.setValue(value);
        return subclass;
      });
}
 
Example #13
Source File: DimEncodingPreserveOrderTest.java    From kylin-on-parquet-v2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testOneMoreByteVLongDimEncPreserveOrder() {
    // TODO: better test
    OneMoreByteVLongDimEnc enc = new OneMoreByteVLongDimEnc(2);
    List<ByteArray> encodedValues = Lists.newArrayList();
    encodedValues.add(encode(enc, -32768L));
    encodedValues.add(encode(enc, -10000L));
    encodedValues.add(encode(enc, -100L));
    encodedValues.add(encode(enc, 0L));
    encodedValues.add(encode(enc, 100L));
    encodedValues.add(encode(enc, 10000L));
    encodedValues.add(encode(enc, 32767L));
    encodedValues.add(encode(enc, null));

    assertTrue(Ordering.from(new DefaultGTComparator()).isOrdered(encodedValues));
}
 
Example #14
Source File: BlazeAndroidRunConfigurationValidationUtil.java    From intellij with Apache License 2.0 6 votes vote down vote up
public static void validateExecution(
    @Nullable Module module,
    @Nullable AndroidFacet facet,
    @Nullable ProjectViewSet projectViewSet)
    throws ExecutionException {
  List<ValidationError> errors = Lists.newArrayList();
  errors.addAll(validateModule(module));
  if (module != null) {
    errors.addAll(validateFacet(facet, module));
  }
  if (projectViewSet == null) {
    errors.add(ValidationError.fatal("Could not load project view. Please resync project"));
  }

  if (errors.isEmpty()) {
    return;
  }
  ValidationError topError = Ordering.natural().max(errors);
  if (topError.isFatal()) {
    throw new ExecutionException(topError.getMessage());
  }
}
 
Example #15
Source File: AdminServiceImpl.java    From pinpoint with Apache License 2.0 6 votes vote down vote up
@Override
public void removeInactiveAgents(int durationDays) {
    if (durationDays < MIN_DURATION_DAYS_FOR_INACTIVITY) {
        throw new IllegalArgumentException("duration may not be less than " + MIN_DURATION_DAYS_FOR_INACTIVITY + " days");
    }
    Map<String, List<String>> inactiveAgentMap = new TreeMap<>(Ordering.usingToString());

    List<Application> applications = this.applicationIndexDao.selectAllApplicationNames();
    Set<String> applicationNames = new TreeSet<>(Ordering.usingToString());
    // remove duplicates (same application name but different service type)
    for (Application application : applications) {
        applicationNames.add(application.getName());
    }
    for (String applicationName : applicationNames) {
        List<String> agentIds = this.applicationIndexDao.selectAgentIds(applicationName);
        Collections.sort(agentIds);
        List<String> inactiveAgentIds = filterInactiveAgents(agentIds, durationDays);
        if (!CollectionUtils.isEmpty(inactiveAgentIds)) {
            inactiveAgentMap.put(applicationName, inactiveAgentIds);
        }
    }
    // map may become big, but realistically won't cause OOM
    // if it becomes an issue, consider deleting inside the loop above
    logger.info("deleting {}", inactiveAgentMap);
    this.applicationIndexDao.deleteAgentIds(inactiveAgentMap);
}
 
Example #16
Source File: CollectionSearchTests.java    From java_in_examples with Apache License 2.0 5 votes vote down vote up
private static void testGetMin() {
    Collection<String> collection = Lists.newArrayList("5", "1", "3", "8", "4");
    OrderedIterable<String> orderedIterable = FastList.newListWith("5", "1", "3", "8", "4");
    Iterable<String> iterable = collection;

    // get min element
    String jdk = Collections.min(collection); // using JDK
    String gs = orderedIterable.min(); // using GS
    String guava = Ordering.natural().min(iterable); // using guava
    System.out.println("min = " + jdk + ":" + guava + ":" + gs); // print min = 1:1:1
}
 
Example #17
Source File: MCRRestDerivateContents.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int compareTo(DirectoryEntry o) {
    return Ordering
        .<DirectoryEntry> from((de1, de2) -> {
            if (de1 instanceof Directory && !(de2 instanceof Directory)) {
                return -1;
            }
            if (de1.getClass().equals(de2.getClass())) {
                return 0;
            }
            return 1;
        })
        .compound((de1, de2) -> de1.getName().compareTo(de2.getName()))
        .compare(this, o);
}
 
Example #18
Source File: ConfigGuiFactory.java    From OpenPeripheral with MIT License 5 votes vote down vote up
private static Collection<String> sorted(Collection<String> c) {
	final List<String> results = Lists.newArrayList(c);
	Collections.sort(results, Ordering.natural().onResultOf(new Function<String, String>() {
		@Override
		@Nullable
		public String apply(@Nullable String input) {
			return input != null? input.toLowerCase() : null;
		}
	}));
	return results;
}
 
Example #19
Source File: FeatureFlagManualTrimmingTest.java    From bazel with Apache License 2.0 5 votes vote down vote up
private ImmutableSortedMap<Label, String> getFlagValuesFromOutputFile(Artifact flagDict) {
  String fileContents =
      ((FileWriteAction) getActionGraph().getGeneratingAction(flagDict)).getFileContents();
  return Splitter.on('\n')
      .withKeyValueSeparator(":::")
      .split(fileContents)
      .entrySet()
      .stream()
      .collect(
          toImmutableSortedMap(
              Ordering.natural(),
              (entry) -> Label.parseAbsoluteUnchecked(entry.getKey()),
              Map.Entry::getValue));
}
 
Example #20
Source File: ExpressTrainModifier.java    From Rails with GNU General Public License v2.0 5 votes vote down vote up
private List<NetworkVertex> extractExpressRun(RevenueTrainRun run, int length) {

            // check for valid run first
            if (!run.hasAValidRun()) return new ArrayList<NetworkVertex>();

            // create a sorted list of the run vertices
            List<NetworkVertex> sortedVertices =
                    Ordering.from(new NetworkVertex.ValueOrder()).immutableSortedCopy(run.getUniqueVertices());

            ImmutableList.Builder<NetworkVertex> expressVertices = ImmutableList.builder();
            NetworkVertex baseVertex = run.getBaseVertex();
            expressVertices.add(baseVertex);

            int inRunNumber = 1;
            for (NetworkVertex vertex:sortedVertices) {
                if (vertex != baseVertex) {
                    if (!vertex.isStation()) {
                        // keep ferry malus vertices
                        expressVertices.add(vertex);
                    } else if (inRunNumber < length) {
                        // add vertices until length is reached
                        expressVertices.add(vertex);
                        inRunNumber ++;
                    }
                }
            }

            return expressVertices.build();
        }
 
Example #21
Source File: CheckResourceUtil.java    From dsl-devkit with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Looks up all exported grammars.
 *
 * @return an iterable of grammar
 */
public List<Grammar> getGrammars() {
  Iterable<Grammar> result = allGrammars();

  Ordering<Grammar> byNameOrdering = new Ordering<Grammar>() {
    @Override
    public int compare(final Grammar left, final Grammar right) {
      return Ordering.<String> natural().compare(new GrammarHelper(left).getLabelName(), new GrammarHelper(right).getLabelName());
    }
  };
  return byNameOrdering.sortedCopy(Sets.newHashSet(Iterables.filter(result, Predicates.notNull())));
}
 
Example #22
Source File: AarGeneratorAction.java    From bazel with Apache License 2.0 5 votes vote down vote up
void writeEntries() throws IOException {
  for (Path dir : Ordering.natural().immutableSortedCopy(directories)) {
    writeDirectoryEntry(dir);
  }
  for (Path file : Ordering.natural().immutableSortedCopy(files)) {
    writeFileEntry(file);
  }
}
 
Example #23
Source File: Registry.java    From nomulus with Apache License 2.0 5 votes vote down vote up
/** Sets the TLD state to transition to the specified states at the specified times. */
public Builder setTldStateTransitions(ImmutableSortedMap<DateTime, TldState> tldStatesMap) {
  checkNotNull(tldStatesMap, "TLD states map cannot be null");
  // Filter out any entries with QUIET_PERIOD as the value before checking for ordering, since
  // that phase is allowed to appear anywhere.
  checkArgument(
      Ordering.natural()
          .isStrictlyOrdered(
              Iterables.filter(tldStatesMap.values(), not(equalTo(TldState.QUIET_PERIOD)))),
      "The TLD states are chronologically out of order");
  getInstance().tldStateTransitions =
      TimedTransitionProperty.fromValueMap(tldStatesMap, TldStateTransition.class);
  return this;
}
 
Example #24
Source File: AdviceOrderingTest.java    From glowroot with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldCompare() {
    Ordering<Advice> ordering = Advice.ordering;
    assertThat(ordering.compare(advicePriority1, advicePriority2)).isNegative();
    assertThat(ordering.compare(advicePriority2, advicePriority1)).isPositive();
    assertThat(ordering.compare(adviceTimerNameA, adviceTimerNameB)).isNegative();
    assertThat(ordering.compare(adviceTimerNameB, adviceTimerNameA)).isPositive();
    assertThat(ordering.compare(adviceTimerNameA, adviceTimerNameEmpty1)).isNegative();
    assertThat(ordering.compare(adviceTimerNameEmpty1, adviceTimerNameA)).isPositive();
    assertThat(ordering.compare(adviceTimerNameEmpty1, adviceTimerNameEmpty2)).isZero();
    assertThat(ordering.compare(adviceTimerNameEmpty2, adviceTimerNameEmpty1)).isZero();
}
 
Example #25
Source File: MediaType.java    From vertx-rest-client with Apache License 2.0 5 votes vote down vote up
/**
 * Sorts the given list of {@code MediaType} objects by specificity as the
 * primary criteria and quality value the secondary.
 *
 * @see MediaType#sortBySpecificity(List)
 * @see MediaType#sortByQualityValue(List)
 */
public static void sortBySpecificityAndQuality(List<MediaType> mediaTypes) {
    checkNotNull(mediaTypes, "'mediaTypes' must not be null");
    if (mediaTypes.size() > 1) {
        Collections.sort(mediaTypes, Ordering.compound(
                ImmutableList.of(MediaType.SPECIFICITY_COMPARATOR, MediaType.QUALITY_VALUE_COMPARATOR)));
    }
}
 
Example #26
Source File: FunctionIdent.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public int compareTo(FunctionIdent o) {
    return ComparisonChain.start()
            .compare(name, o.name)
            .compare(argumentTypes, o.argumentTypes, Ordering.<DataType>natural().lexicographical())
            .result();
}
 
Example #27
Source File: VersionNumber.java    From Pushjet-Android with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public int compareTo(VersionNumber other) {
    if (major != other.major) {
        return major - other.major;
    }
    if (minor != other.minor) {
        return minor - other.minor;
    }
    if (micro != other.micro) {
        return micro - other.micro;
    }
    if (patch != other.patch) {
        return patch - other.patch;
    }
    return Ordering.natural().nullsLast().compare(toLowerCase(qualifier), toLowerCase(other.qualifier));
}
 
Example #28
Source File: JsonConcatenateStep.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public StepExecutionResult execute(ExecutionContext context) throws IOException {
  ImmutableSortedSet<Path> filesToConcatenate =
      inputs.stream()
          .map(input -> filesystem.getRootPath().resolve(input).getPath())
          .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()));
  AbsPath destination = filesystem.getRootPath().resolve(output);
  new JsonConcatenator(filesToConcatenate, destination.getPath(), filesystem).concatenate();
  return StepExecutionResults.SUCCESS;
}
 
Example #29
Source File: JsBundleDescription.java    From buck with Apache License 2.0 5 votes vote down vote up
private TransitiveLibraryDependencies(
    BuildTarget bundleTarget, TargetGraph targetGraph, ActionGraphBuilder graphBuilder) {
  this.targetGraph = targetGraph;
  this.graphBuilder = graphBuilder;

  FlavorSet bundleFlavors = bundleTarget.getFlavors();
  extraFlavors =
      bundleFlavors.getSet().stream()
          .filter(
              flavor ->
                  JsLibraryDescription.FLAVOR_DOMAINS.stream()
                      .anyMatch(domain -> domain.contains(flavor)))
          .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural()));
}
 
Example #30
Source File: FastqTracker.java    From hmftools with GNU General Public License v3.0 5 votes vote down vote up
@NotNull
FastqTracker addToSample(@NotNull final String sample, @NotNull final String lane, @NotNull final FastqData data) {
    final Map<String, Map<String, FastqData>> newSamples;
    if (!samples.containsKey(sample)) {
        newSamples = addToMap(samples, sample,
                new ImmutableSortedMap.Builder<String, FastqData>(Ordering.natural()).put(lane, data).build());
    } else if (!samples.get(sample).containsKey(lane)) {
        newSamples = addToMap(samples, sample, addToMap(samples.get(sample), lane, data));
    } else {
        final FastqData currentValue = samples.get(sample).get(lane);
        final FastqData newValue = currentValue.add(data);
        newSamples = addToMap(samples, sample, addToMap(samples.get(sample), lane, newValue));
    }
    return new FastqTracker(newSamples);
}