Java Code Examples for com.google.common.collect.ImmutableMultiset

The following are top voted examples for showing how to use com.google.common.collect.ImmutableMultiset. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: guava-beta-checker   File: TestCompiler.java   View source code 6 votes vote down vote up
/**
 * Asserts that the given diagnostics contain errors with a message containing "[CheckerName]"
 * on the given lines of the given file. If there should be multiple errors on a line, the line
 * number must appear multiple times. There may not be any errors in any other file.
 */
public void assertErrorsOnLines(String file,
    List<Diagnostic<? extends JavaFileObject>> diagnostics, long... lines) {
  ListMultimap<String, Long> actualErrors = ArrayListMultimap.create();
  for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
    String message = diagnostic.getMessage(Locale.US);

    // The source may be null, e.g. for diagnostics about command-line flags
    assertNotNull(message, diagnostic.getSource());
    String sourceName = diagnostic.getSource().getName();

    assertEquals(
        "unexpected error in source file " + sourceName + ": " + message,
        file, sourceName);

    actualErrors.put(diagnostic.getSource().getName(), diagnostic.getLineNumber());

    // any errors from the compiler that are not related to this checker should fail
    assertThat(message).contains("[" + checker.getAnnotation(BugPattern.class).name() + "]");
  }

  assertEquals(
      ImmutableMultiset.copyOf(Longs.asList(lines)),
      ImmutableMultiset.copyOf(actualErrors.get(file)));
}
 
Example 2
Project: flow-platform   File: PluginServiceTest.java   View source code 6 votes vote down vote up
@Test
public void should_stop_success_demo_first() throws Throwable {
    cleanFolder("flowCliE");

    CountDownLatch countDownLatch = new CountDownLatch(1);
    applicationEventMulticaster.addApplicationListener((ApplicationListener<PluginStatusChangeEvent>) event -> {
        if (ImmutableMultiset.of(PluginStatus.INSTALLING).contains(event.getPluginStatus())) {
            countDownLatch.countDown();
        }
    });

    pluginService.install("flowCliE");
    countDownLatch.await(30, TimeUnit.SECONDS);
    pluginService.stop("flowCliE");

    Plugin plugin = pluginDao.get("flowCliE");
    Assert.assertEquals(PluginStatus.PENDING, plugin.getStatus());
    Assert.assertEquals(false, plugin.getStopped());
}
 
Example 3
Project: CustomWorldGen   File: Loader.java   View source code 6 votes vote down vote up
private void identifyDuplicates(List<ModContainer> mods)
{
    TreeMultimap<ModContainer, File> dupsearch = TreeMultimap.create(new ModIdComparator(), Ordering.arbitrary());
    for (ModContainer mc : mods)
    {
        if (mc.getSource() != null)
        {
            dupsearch.put(mc, mc.getSource());
        }
    }

    ImmutableMultiset<ModContainer> duplist = Multisets.copyHighestCountFirst(dupsearch.keys());
    SetMultimap<ModContainer, File> dupes = LinkedHashMultimap.create();
    for (Entry<ModContainer> e : duplist.entrySet())
    {
        if (e.getCount() > 1)
        {
            FMLLog.severe("Found a duplicate mod %s at %s", e.getElement().getModId(), dupsearch.get(e.getElement()));
            dupes.putAll(e.getElement(),dupsearch.get(e.getElement()));
        }
    }
    if (!dupes.isEmpty())
    {
        throw new DuplicateModsFoundException(dupes);
    }
}
 
Example 4
Project: Mastering-Mesos   File: AttributeAggregate.java   View source code 6 votes vote down vote up
@VisibleForTesting
static AttributeAggregate create(Supplier<Iterable<IAttribute>> attributes) {
  Supplier<Multiset<Pair<String, String>>> aggregator = Suppliers.compose(
      attributes1 -> {
        ImmutableMultiset.Builder<Pair<String, String>> builder = ImmutableMultiset.builder();
        for (IAttribute attribute : attributes1) {
          for (String value : attribute.getValues()) {
            builder.add(Pair.of(attribute.getName(), value));
          }
        }

        return builder.build();
      },
      attributes
  );

  return new AttributeAggregate(aggregator);
}
 
Example 5
Project: TRHS_Club_Mod_2016   File: Loader.java   View source code 6 votes vote down vote up
private void identifyDuplicates(List<ModContainer> mods)
{
    TreeMultimap<ModContainer, File> dupsearch = TreeMultimap.create(new ModIdComparator(), Ordering.arbitrary());
    for (ModContainer mc : mods)
    {
        if (mc.getSource() != null)
        {
            dupsearch.put(mc, mc.getSource());
        }
    }

    ImmutableMultiset<ModContainer> duplist = Multisets.copyHighestCountFirst(dupsearch.keys());
    SetMultimap<ModContainer, File> dupes = LinkedHashMultimap.create();
    for (Entry<ModContainer> e : duplist.entrySet())
    {
        if (e.getCount() > 1)
        {
            FMLLog.severe("Found a duplicate mod %s at %s", e.getElement().getModId(), dupsearch.get(e.getElement()));
            dupes.putAll(e.getElement(),dupsearch.get(e.getElement()));
        }
    }
    if (!dupes.isEmpty())
    {
        throw new DuplicateModsFoundException(dupes);
    }
}
 
Example 6
Project: grakn   File: FibonacciQueueTest.java   View source code 6 votes vote down vote up
@Test
public void testLotsOfRandomInserts() {
    int lots = 50000;
    final FibonacciQueue<Integer> queue = FibonacciQueue.create();
    // Insert lots of random numbers.
    final ImmutableMultiset.Builder<Integer> insertedBuilder = ImmutableMultiset.builder();
    final Random random = new Random();
    for (int i = 0; i < lots; i++) {
        int r = random.nextInt();
        insertedBuilder.add(r);
        queue.add(r);
    }
    final Multiset<Integer> inserted = insertedBuilder.build();
    assertEquals(lots, queue.size());
    // Ensure it contains the same multiset of values that we put in
    assertEquals(inserted, ImmutableMultiset.copyOf(queue));
    // Ensure the numbers come out in increasing order.
    final List<Integer> polled = Lists.newLinkedList();
    while (!queue.isEmpty()) {
        polled.add(queue.poll());
    }
    assertTrue(Ordering.<Integer>natural().isOrdered(polled));
    // Ensure the same multiset of values came out that we put in
    assertEquals(inserted, ImmutableMultiset.copyOf(polled));
    assertEquals(0, queue.size());
}
 
Example 7
Project: opencensus-java   File: TagContext.java   View source code 6 votes vote down vote up
/**
 * Returns true iff the other object is an instance of {@code TagContext} and contains the same
 * key-value pairs. Implementations are free to override this method to provide better
 * performance.
 */
@Override
public boolean equals(@Nullable Object other) {
  if (!(other instanceof TagContext)) {
    return false;
  }
  TagContext otherTags = (TagContext) other;
  Iterator<Tag> iter1 = getIterator();
  Iterator<Tag> iter2 = otherTags.getIterator();
  Multiset<Tag> tags1 =
      iter1 == null
          ? ImmutableMultiset.<Tag>of()
          : HashMultiset.create(Lists.<Tag>newArrayList(iter1));
  Multiset<Tag> tags2 =
      iter2 == null
          ? ImmutableMultiset.<Tag>of()
          : HashMultiset.create(Lists.<Tag>newArrayList(iter2));
  return tags1.equals(tags2);
}
 
Example 8
Project: FreeBuilder   File: MultisetProperty.java   View source code 6 votes vote down vote up
@Override
public Optional<MultisetProperty> create(Config config) {
  DeclaredType type = maybeDeclared(config.getProperty().getType()).orNull();
  if (type == null || !erasesToAnyOf(type, Multiset.class, ImmutableMultiset.class)) {
    return Optional.absent();
  }

  TypeMirror elementType = upperBound(config.getElements(), type.getTypeArguments().get(0));
  Optional<TypeMirror> unboxedType = maybeUnbox(elementType, config.getTypes());
  boolean needsSafeVarargs = needsSafeVarargs(unboxedType.or(elementType));
  boolean overridesSetCountMethod =
      hasSetCountMethodOverride(config, unboxedType.or(elementType));
  boolean overridesVarargsAddMethod =
      hasVarargsAddMethodOverride(config, unboxedType.or(elementType));
  return Optional.of(new MultisetProperty(
      config.getMetadata(),
      config.getProperty(),
      needsSafeVarargs,
      overridesSetCountMethod,
      overridesVarargsAddMethod,
      elementType,
      unboxedType));
}
 
Example 9
Project: FreeBuilder   File: MultisetPrefixlessPropertyTest.java   View source code 6 votes vote down vote up
@Test
public void testImmutableSetProperty() {
  behaviorTester
      .with(new Processor(features))
      .with(new SourceBuilder()
          .addLine("package com.example;")
          .addLine("@%s", FreeBuilder.class)
          .addLine("public abstract class DataType {")
          .addLine("  public abstract %s<%s> items();", ImmutableMultiset.class, String.class)
          .addLine("")
          .addLine("  public static class Builder extends DataType_Builder {}")
          .addLine("  public static Builder builder() {")
          .addLine("    return new Builder();")
          .addLine("  }")
          .addLine("}")
          .build())
      .with(testBuilder()
          .addLine("DataType value = new DataType.Builder()")
          .addLine("    .addItems(\"one\")")
          .addLine("    .addItems(\"two\")")
          .addLine("    .build();")
          .addLine("assertThat(value.items()).iteratesAs(\"one\", \"two\");")
          .build())
      .runTest();
}
 
Example 10
Project: FreeBuilder   File: MultisetBeanPropertyTest.java   View source code 6 votes vote down vote up
@Test
public void testImmutableSetProperty() {
  behaviorTester
      .with(new Processor(features))
      .with(new SourceBuilder()
          .addLine("package com.example;")
          .addLine("@%s", FreeBuilder.class)
          .addLine("public abstract class DataType {")
          .addLine("  public abstract %s<%s> getItems();", ImmutableMultiset.class, String.class)
          .addLine("")
          .addLine("  public static class Builder extends DataType_Builder {}")
          .addLine("  public static Builder builder() {")
          .addLine("    return new Builder();")
          .addLine("  }")
          .addLine("}")
          .build())
      .with(new TestBuilder()
          .addLine("com.example.DataType value = new com.example.DataType.Builder()")
          .addLine("    .addItems(\"one\")")
          .addLine("    .addItems(\"two\")")
          .addLine("    .build();")
          .addLine("assertThat(value.getItems()).iteratesAs(\"one\", \"two\");")
          .build())
      .runTest();
}
 
Example 11
Project: CauldronGit   File: Loader.java   View source code 6 votes vote down vote up
private void identifyDuplicates(List<ModContainer> mods)
{
    TreeMultimap<ModContainer, File> dupsearch = TreeMultimap.create(new ModIdComparator(), Ordering.arbitrary());
    for (ModContainer mc : mods)
    {
        if (mc.getSource() != null)
        {
            dupsearch.put(mc, mc.getSource());
        }
    }

    ImmutableMultiset<ModContainer> duplist = Multisets.copyHighestCountFirst(dupsearch.keys());
    SetMultimap<ModContainer, File> dupes = LinkedHashMultimap.create();
    for (Entry<ModContainer> e : duplist.entrySet())
    {
        if (e.getCount() > 1)
        {
            FMLLog.severe("Found a duplicate mod %s at %s", e.getElement().getModId(), dupsearch.get(e.getElement()));
            dupes.putAll(e.getElement(),dupsearch.get(e.getElement()));
        }
    }
    if (!dupes.isEmpty())
    {
        throw new DuplicateModsFoundException(dupes);
    }
}
 
Example 12
Project: mathosphere   File: MathTagTest.java   View source code 6 votes vote down vote up
@Test
public void testGetIdentifier() throws Exception {
    MathTag tagX = new MathTag(1, "<math xmlns=\"http://www.w3.org/1998/Math/MathML\"><mrow><mi>x</mi></mrow></math>", WikiTextUtils.MathMarkUpType.MATHML);
    assertEquals(ImmutableSet.of("x"), tagX.getIdentifier(true, true).elementSet());
    assertEquals(ImmutableSet.of("x"), tagX.getIdentifier(false, true).elementSet());
    MathTag schrödinger = new MathTag(1, getTestResource("com/formulasearchengine/mathosphere/mlp/schrödinger_eq.xml"), WikiTextUtils.MathMarkUpType.MATHML);
    //MathTag schrödingerTex = new MathTag(1,"i\\hbar\\frac{\\partial}{\\partial t}\\Psi(\\mathbb{r},\\,t)=-\\frac{\\hbar^{2}}{2m}" +
    //  "\\nabla^{2}\\Psi(\\mathbb{r},\\,t)+V(\\mathbb{r})\\Psi(\\mathbb{r},\\,t).", WikiTextUtils.MathMarkUpType.LATEX);
    ImmutableMultiset<String> lIds = ImmutableMultiset.of("i",
            "\\hbar", "\\hbar",
            "t", "t", "t", "t",
            "\\Psi", "\\Psi", "\\Psi",
            "\\mathbb{r}", "\\mathbb{r}", "\\mathbb{r}", "\\mathbb{r}",
            "V",
            "m");
    assertEquals(lIds, schrödinger.getIdentifier(true, false));
}
 
Example 13
Project: guava   File: NullPointerTesterTest.java   View source code 6 votes vote down vote up
final void check() {
  runTester()
      .assertNonNullValues(
          Gender.MALE,
          Integer.valueOf(0),
          0,
          "",
          "",
          ImmutableList.of(),
          ImmutableList.of(),
          ImmutableMap.of(),
          ImmutableMap.of(),
          ImmutableSet.of(),
          ImmutableSet.of(),
          ImmutableSortedSet.of(),
          ImmutableSortedSet.of(),
          ImmutableMultiset.of(),
          ImmutableMultiset.of(),
          ImmutableMultimap.of(),
          ImmutableMultimap.of(),
          ImmutableTable.of(),
          ImmutableTable.of());
}
 
Example 14
Project: guava   File: NullPointerTesterTest.java   View source code 6 votes vote down vote up
final void check() {
  runTester()
      .assertNonNullValues(
          Gender.MALE,
          Integer.valueOf(0),
          0,
          "",
          "",
          ImmutableList.of(),
          ImmutableList.of(),
          ImmutableMap.of(),
          ImmutableMap.of(),
          ImmutableSet.of(),
          ImmutableSet.of(),
          ImmutableSortedSet.of(),
          ImmutableSortedSet.of(),
          ImmutableMultiset.of(),
          ImmutableMultiset.of(),
          ImmutableMultimap.of(),
          ImmutableMultimap.of(),
          ImmutableTable.of(),
          ImmutableTable.of());
}
 
Example 15
Project: protobuf-el   File: CommonMatchersTest.java   View source code 6 votes vote down vote up
@Parameters(name = "{index}:immutable={1}")
public static Collection<Object[]> data() {
  return ImmutableList.of(
      //Mutable collections
      new Object[]{Lists.newArrayList(1, 2, 3), false},
      new Object[]{Sets.newHashSet("1", "2"), false},
      new Object[]{Collection.class.cast(Lists.newArrayList(true, false)), false},
      //Immutable collections
      new Object[]{ImmutableList.of(1, 2, 3), true},
      new Object[]{ImmutableSet.of("1", "2"), true},
      new Object[]{ImmutableSortedSet.of(1, 2, 3), true},
      new Object[]{ImmutableMultiset.of(1, 2, 3), true},
      new Object[]{Collection.class.cast(ImmutableList.of(true, false)), true},
      new Object[]{Collections.unmodifiableList(Lists.newArrayList(1, 2, 3)), true},
      new Object[]{Collections.unmodifiableSet(Sets.newHashSet("1", "2")), true},
      new Object[]{Collections.unmodifiableCollection(Lists.newArrayList(true, false)), true}
      );
}
 
Example 16
Project: Cauldron   File: Loader.java   View source code 6 votes vote down vote up
private void identifyDuplicates(List<ModContainer> mods)
{
    TreeMultimap<ModContainer, File> dupsearch = TreeMultimap.create(new ModIdComparator(), Ordering.arbitrary());
    for (ModContainer mc : mods)
    {
        if (mc.getSource() != null)
        {
            dupsearch.put(mc, mc.getSource());
        }
    }

    ImmutableMultiset<ModContainer> duplist = Multisets.copyHighestCountFirst(dupsearch.keys());
    SetMultimap<ModContainer, File> dupes = LinkedHashMultimap.create();
    for (Entry<ModContainer> e : duplist.entrySet())
    {
        if (e.getCount() > 1)
        {
            FMLLog.severe("Found a duplicate mod %s at %s", e.getElement().getModId(), dupsearch.get(e.getElement()));
            dupes.putAll(e.getElement(),dupsearch.get(e.getElement()));
        }
    }
    if (!dupes.isEmpty())
    {
        throw new DuplicateModsFoundException(dupes);
    }
}
 
Example 17
Project: Cauldron   File: Loader.java   View source code 6 votes vote down vote up
private void identifyDuplicates(List<ModContainer> mods)
{
    TreeMultimap<ModContainer, File> dupsearch = TreeMultimap.create(new ModIdComparator(), Ordering.arbitrary());
    for (ModContainer mc : mods)
    {
        if (mc.getSource() != null)
        {
            dupsearch.put(mc, mc.getSource());
        }
    }

    ImmutableMultiset<ModContainer> duplist = Multisets.copyHighestCountFirst(dupsearch.keys());
    SetMultimap<ModContainer, File> dupes = LinkedHashMultimap.create();
    for (Entry<ModContainer> e : duplist.entrySet())
    {
        if (e.getCount() > 1)
        {
            FMLLog.severe("Found a duplicate mod %s at %s", e.getElement().getModId(), dupsearch.get(e.getElement()));
            dupes.putAll(e.getElement(),dupsearch.get(e.getElement()));
        }
    }
    if (!dupes.isEmpty())
    {
        throw new DuplicateModsFoundException(dupes);
    }
}
 
Example 18
Project: Cauldron   File: Loader.java   View source code 6 votes vote down vote up
private void identifyDuplicates(List<ModContainer> mods)
{
    TreeMultimap<ModContainer, File> dupsearch = TreeMultimap.create(new ModIdComparator(), Ordering.arbitrary());
    for (ModContainer mc : mods)
    {
        if (mc.getSource() != null)
        {
            dupsearch.put(mc, mc.getSource());
        }
    }

    ImmutableMultiset<ModContainer> duplist = Multisets.copyHighestCountFirst(dupsearch.keys());
    SetMultimap<ModContainer, File> dupes = LinkedHashMultimap.create();
    for (Entry<ModContainer> e : duplist.entrySet())
    {
        if (e.getCount() > 1)
        {
            FMLLog.severe("Found a duplicate mod %s at %s", e.getElement().getModId(), dupsearch.get(e.getElement()));
            dupes.putAll(e.getElement(),dupsearch.get(e.getElement()));
        }
    }
    if (!dupes.isEmpty())
    {
        throw new DuplicateModsFoundException(dupes);
    }
}
 
Example 19
Project: simhashdb   File: SimpleCounting.java   View source code 6 votes vote down vote up
@Override
public Map<String, Double> count(final List<List<String>> sentences) {
	if (sentences == null || sentences.size() == 0) {
		return Collections.emptyMap();
	}
	final List<String> words = new ArrayList<>();
	for (final List<String> sentence : sentences) {
		words.addAll(sentence);
	}
	final ImmutableMultiset<String> multiset = ImmutableMultiset
			.copyOf(words);
	final Map<String, Double> result = new HashMap<>();
	for (final String word : multiset.elementSet()) {
		result.put(word, (double) multiset.count(word));
	}
	return result;
}
 
Example 20
Project: RuneCraftery   File: Loader.java   View source code 6 votes vote down vote up
private void identifyDuplicates(List<ModContainer> mods)
{
    TreeMultimap<ModContainer, File> dupsearch = TreeMultimap.create(new ModIdComparator(), Ordering.arbitrary());
    for (ModContainer mc : mods)
    {
        if (mc.getSource() != null)
        {
            dupsearch.put(mc, mc.getSource());
        }
    }

    ImmutableMultiset<ModContainer> duplist = Multisets.copyHighestCountFirst(dupsearch.keys());
    SetMultimap<ModContainer, File> dupes = LinkedHashMultimap.create();
    for (Entry<ModContainer> e : duplist.entrySet())
    {
        if (e.getCount() > 1)
        {
            FMLLog.severe("Found a duplicate mod %s at %s", e.getElement().getModId(), dupsearch.get(e.getElement()));
            dupes.putAll(e.getElement(),dupsearch.get(e.getElement()));
        }
    }
    if (!dupes.isEmpty())
    {
        throw new DuplicateModsFoundException(dupes);
    }
}
 
Example 21
Project: RuneCraftery   File: Loader.java   View source code 6 votes vote down vote up
private void identifyDuplicates(List<ModContainer> mods)
{
    TreeMultimap<ModContainer, File> dupsearch = TreeMultimap.create(new ModIdComparator(), Ordering.arbitrary());
    for (ModContainer mc : mods)
    {
        if (mc.getSource() != null)
        {
            dupsearch.put(mc, mc.getSource());
        }
    }

    ImmutableMultiset<ModContainer> duplist = Multisets.copyHighestCountFirst(dupsearch.keys());
    SetMultimap<ModContainer, File> dupes = LinkedHashMultimap.create();
    for (Entry<ModContainer> e : duplist.entrySet())
    {
        if (e.getCount() > 1)
        {
            FMLLog.severe("Found a duplicate mod %s at %s", e.getElement().getModId(), dupsearch.get(e.getElement()));
            dupes.putAll(e.getElement(),dupsearch.get(e.getElement()));
        }
    }
    if (!dupes.isEmpty())
    {
        throw new DuplicateModsFoundException(dupes);
    }
}
 
Example 22
Project: BetterNutritionMod   File: Loader.java   View source code 6 votes vote down vote up
private void identifyDuplicates(List<ModContainer> mods)
{
    TreeMultimap<ModContainer, File> dupsearch = TreeMultimap.create(new ModIdComparator(), Ordering.arbitrary());
    for (ModContainer mc : mods)
    {
        if (mc.getSource() != null)
        {
            dupsearch.put(mc, mc.getSource());
        }
    }

    ImmutableMultiset<ModContainer> duplist = Multisets.copyHighestCountFirst(dupsearch.keys());
    SetMultimap<ModContainer, File> dupes = LinkedHashMultimap.create();
    for (Entry<ModContainer> e : duplist.entrySet())
    {
        if (e.getCount() > 1)
        {
            FMLLog.severe("Found a duplicate mod %s at %s", e.getElement().getModId(), dupsearch.get(e.getElement()));
            dupes.putAll(e.getElement(),dupsearch.get(e.getElement()));
        }
    }
    if (!dupes.isEmpty())
    {
        throw new DuplicateModsFoundException(dupes);
    }
}
 
Example 23
Project: molgenis   File: ParserTest.java   View source code 6 votes vote down vote up
@Test
public void testTransform()
{
	List<String> lines = Arrays.asList("#Comment line", "#Another comment line",
			"11\t47359281\t.\tC\tG\t.\t.\tCADD_SCALED=33.0", "11\t47359281\tC\tCC\t2.3\t33.0",
			"11\t47359281\t.\tC\tCG\t.\t.\tCADD_SCALED=33.0", "11\t47359281\t.\tCG\tC\t.\t.\tCADD_SCALED=33.0");

	Multiset<LineType> expected = ImmutableMultiset.of(COMMENT, COMMENT, VCF, CADD, INDEL_NOCADD, INDEL_NOCADD);
	Assert.assertEquals(lineParser.transformLines(lines.stream(), output, error), expected);

	verify(output).accept("##fileformat=VCFv4.0");
	verify(output).accept("#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO");
	verify(output).accept("11\t47359281\t.\tC\tG\t.\t.\t.");
	verify(output).accept("11\t47359281\t.\tC\tCC\t.\t.\tCADD=2.3;CADD_SCALED=33.0");
	verify(error).accept("Line 5:\t11\t47359281\t.\tC\tCG\t.\t.\tCADD_SCALED=33.0");
	verify(error).accept("Line 6:\t11\t47359281\t.\tCG\tC\t.\t.\tCADD_SCALED=33.0");
}
 
Example 24
Project: gwt-jackson   File: MultisetGwtTest.java   View source code 6 votes vote down vote up
public void testSerialization() {
    BeanWithMultisetTypes bean = new BeanWithMultisetTypes();

    List<String> list = Arrays.asList( "foo", "abc", null, "abc" );
    List<String> listWithNonNull = Arrays.asList( "foo", "abc", "bar", "abc" );

    bean.multiset = LinkedHashMultiset.create( list );
    bean.hashMultiset = HashMultiset.create( Arrays.asList( "abc", "abc" ) );
    bean.linkedHashMultiset = LinkedHashMultiset.create( list );
    bean.sortedMultiset = TreeMultiset.create( listWithNonNull );
    bean.treeMultiset = TreeMultiset.create( listWithNonNull );
    bean.immutableMultiset = ImmutableMultiset.copyOf( listWithNonNull );
    bean.enumMultiset = EnumMultiset.create( Arrays.asList( AlphaEnum.B, AlphaEnum.A, AlphaEnum.D, AlphaEnum.A ) );

    String expected = "{" +
            "\"multiset\":[\"foo\",\"abc\",\"abc\",null]," +
            "\"hashMultiset\":[\"abc\",\"abc\"]," +
            "\"linkedHashMultiset\":[\"foo\",\"abc\",\"abc\",null]," +
            "\"sortedMultiset\":[\"abc\",\"abc\",\"bar\",\"foo\"]," +
            "\"treeMultiset\":[\"abc\",\"abc\",\"bar\",\"foo\"]," +
            "\"immutableMultiset\":[\"foo\",\"abc\",\"abc\",\"bar\"]," +
            "\"enumMultiset\":[\"A\",\"A\",\"B\",\"D\"]" +
            "}";

    assertEquals( expected, BeanWithMultisetTypesMapper.INSTANCE.write( bean ) );
}
 
Example 25
Project: gwt-jackson   File: MultisetGwtTest.java   View source code 6 votes vote down vote up
public void testDeserialization() {
    String input = "{" +
            "\"multiset\":[\"foo\",\"abc\",\"abc\",null]," +
            "\"hashMultiset\":[\"abc\",\"abc\"]," +
            "\"linkedHashMultiset\":[\"foo\",\"abc\",\"abc\",null]," +
            "\"sortedMultiset\":[\"foo\",\"abc\",\"bar\",\"abc\",null]," +
            "\"treeMultiset\":[\"bar\",\"abc\",\"abc\",\"foo\",null]," +
            "\"immutableMultiset\":[\"foo\",\"abc\",\"abc\",\"bar\",null]," +
            "\"enumMultiset\":[\"B\",\"A\",\"A\",\"D\",null]" +
            "}";

    BeanWithMultisetTypes result = BeanWithMultisetTypesMapper.INSTANCE.read( input );
    assertNotNull( result );

    List<String> expectedList = Arrays.asList( "foo", "abc", null, "abc" );
    List<String> expectedListWithNonNull = Arrays.asList( "foo", "abc", "bar", "abc" );

    assertEquals( LinkedHashMultiset.create( expectedList ), result.multiset );
    assertEquals( HashMultiset.create( Arrays.asList( "abc", "abc" ) ), result.hashMultiset );
    assertEquals( LinkedHashMultiset.create( expectedList ), result.linkedHashMultiset );
    assertEquals( TreeMultiset.create( expectedListWithNonNull ), result.sortedMultiset );
    assertEquals( TreeMultiset.create( expectedListWithNonNull ), result.treeMultiset );
    assertEquals( ImmutableMultiset.copyOf( expectedListWithNonNull ), result.immutableMultiset );
    assertEquals( EnumMultiset.create( Arrays.asList( AlphaEnum.B, AlphaEnum.A, AlphaEnum.D, AlphaEnum.A ) ), result.enumMultiset );
}
 
Example 26
Project: timbuctoo   File: MappingDocumentBuilder.java   View source code 6 votes vote down vote up
private Set<Multiset<TriplesMapBuilder>> detectCycles(List<TriplesMapBuilder> triplesMapBuilders,
                                                      Map<String, TriplesMapBuilder> lookup) {
  Set<Multiset<TriplesMapBuilder>> cycles = new HashSet<>();
  topologicalSort(
    triplesMapBuilders,
    lookup,
    ((currentChain, current, dependency) -> {
      ImmutableMultiset.Builder<TriplesMapBuilder> cycleChain = ImmutableMultiset.builder();
      cycleChain.addAll(currentChain);
      if (current == dependency) {
        //self reference
        cycleChain.add(dependency);//make sure the self referencing item is counted twice
      }
      cycles.add(cycleChain.build());
    }),
    e -> {
      //errors are handled in the actual sort and ignored for now
    }
  );
  return cycles;
}
 
Example 27
Project: levelup-java-exercises   File: SlotMachineSimulation.java   View source code 6 votes vote down vote up
/**
 * Method should return the number of times an occurrence of a reel
 * 
 * @param reels
 * @return
 */
static int determinePayOutPercentage(List<String> reels) {

	Multiset<String> reelCount = HashMultiset.create();
	reelCount.addAll(reels);

	// order the number of elements by the higest
	ImmutableMultiset<String> highestCountFirst = Multisets.copyHighestCountFirst(reelCount);

	int count = 0;
	for (Entry<String> entry : highestCountFirst.entrySet()) {
		count = entry.getCount();
		break;
	}
	return count;
}
 
Example 28
Project: GitHub   File: StructTest.java   View source code 5 votes vote down vote up
@Test
public void structFromConstructorSerializeDeserialize() throws Exception {
  ImmutableStructFromConstructor structFromConstructor =
      ImmutableStructFromConstructor.of(
          2,
          Arrays.asList(1, 2),
          Optional.of("OPT"),
          ImmutableMultiset.of("list", "list"),
          ImmutableMultimap.of(1, "1"),
          ImmutableListMultimap.of(2, "2"),
          ImmutableBiMap.of(1, "2"))
          .withIndexSet(ImmutableListMultimap.of(3, "3"));

  check(deserialize(serialize(structFromConstructor))).is(structFromConstructor);
}
 
Example 29
Project: tac-kbp-eal   File: GoldArgumentCountsInspector.java   View source code 5 votes vote down vote up
static void writeTsv(ImmutableMultiset<String> data, File file) throws IOException {
  try (Writer out = Files.asCharSink(file, Charsets.UTF_8).openBufferedStream()) {
    for (Entry<String> e : Multisets.copyHighestCountFirst(data).entrySet()) {
      out.write(e.getElement() + "\t" + e.getCount() + "\n");
    }
  }
}
 
Example 30
Project: tac-kbp-eal   File: DerivedQuerySelector2016.java   View source code 5 votes vote down vote up
private ImmutableSetMultimap<RoleAndID, DocAndHopper> indexArgsToEventHopper(final Symbol docID,
    final EREDocument ereDoc, final ImmutableMultiset.Builder<String> allEREEventTypes) {
  final ImmutableSetMultimap.Builder<RoleAndID, DocAndHopper> argsToDocEventsB =
      ImmutableSetMultimap.builder();

  for (final EREEvent ereEvent : ereDoc.getEvents()) {
    boolean loggedType = false;

    for (final EREEventMention ereEventMention : ereEvent.getEventMentions()) {
      for (final EREArgument ereEventArg : ereEventMention.getArguments()) {
        if (ereEventArg instanceof EREEntityArgument) {
          final Optional<EREEntity> entityFiller = ((EREEntityArgument) ereEventArg).ereEntity();
          if (entityFiller.isPresent()) {
            final Optional<Symbol> mappedEventType =
                ScoringUtils.mapERETypesToDotSeparated(ontologyMapper, ereEventMention);
            final Optional<Symbol> mappedEventRole =
                ontologyMapper.eventRole(Symbol.from(ereEventArg.getRole()));

            if (mappedEventType.isPresent() && mappedEventRole.isPresent()) {
              if (!loggedType) {
                // we only want to log events which meet the criteria above, but we only
                // want to count each document event once
                allEREEventTypes.add(mappedEventType.get().asString());
                loggedType = true;
              }
              argsToDocEventsB.put(
                  RoleAndID.of(
                      mappedEventType.get().asString(),
                      mappedEventRole.get().asString(), entityFiller.get().getID()),
                  DocAndHopper.of(docID.asString(), ereEvent.getID(),
                      mappedEventType.get().asString()));
            }
          }
        }
      }
    }
  }

  return argsToDocEventsB.build();
}
 
Example 31
Project: guava-mock   File: MediaType.java   View source code 5 votes vote down vote up
private Map<String, ImmutableMultiset<String>> parametersAsMap() {
  return Maps.transformValues(
      parameters.asMap(),
      new Function<Collection<String>, ImmutableMultiset<String>>() {
        @Override
        public ImmutableMultiset<String> apply(Collection<String> input) {
          return ImmutableMultiset.copyOf(input);
        }
      });
}
 
Example 32
Project: guava-mock   File: NullPointerTesterTest.java   View source code 5 votes vote down vote up
@SuppressWarnings("unused") // called by NullPointerTester
public void checkDefaultValuesForTheseTypes(
    Gender gender,
    Integer integer, int i,
    String string, CharSequence charSequence,
    List<String> list,
    ImmutableList<Integer> immutableList,
    Map<String, Integer> map,
    ImmutableMap<String, String> immutableMap,
    Set<String> set,
    ImmutableSet<Integer> immutableSet,
    SortedSet<Number> sortedSet,
    ImmutableSortedSet<Number> immutableSortedSet,
    Multiset<String> multiset,
    ImmutableMultiset<Integer> immutableMultiset,
    Multimap<String, Integer> multimap,
    ImmutableMultimap<String, Integer> immutableMultimap,
    Table<String, Integer, Exception> table,
    ImmutableTable<Integer, String, Exception> immutableTable) {
  calledWith(
      gender,
      integer, i,
      string, charSequence,
      list, immutableList,
      map, immutableMap,
      set, immutableSet,
      sortedSet, immutableSortedSet,
      multiset, immutableMultiset,
      multimap, immutableMultimap,
      table, immutableTable);
}
 
Example 33
Project: guava-mock   File: NullPointerTesterTest.java   View source code 5 votes vote down vote up
final void check() {
  runTester().assertNonNullValues(
      Gender.MALE,
      Integer.valueOf(0), 0,
      "", "",
      ImmutableList.of(), ImmutableList.of(),
      ImmutableMap.of(), ImmutableMap.of(),
      ImmutableSet.of(), ImmutableSet.of(),
      ImmutableSortedSet.of(), ImmutableSortedSet.of(),
      ImmutableMultiset.of(), ImmutableMultiset.of(),
      ImmutableMultimap.of(), ImmutableMultimap.of(),
      ImmutableTable.of(), ImmutableTable.of());
}
 
Example 34
Project: guava-mock   File: ListenerCallQueueTest.java   View source code 5 votes vote down vote up
private static <T> ImmutableMultiset<T> multiset(Map<T, Integer> counts) {
  ImmutableMultiset.Builder<T> builder = ImmutableMultiset.builder();
  for (Map.Entry<T, Integer> entry : counts.entrySet()) {
    builder.addCopies(entry.getKey(), entry.getValue());
  }
  return builder.build();
}
 
Example 35
Project: ProjectAres   File: IterableUtils.java   View source code 5 votes vote down vote up
public static <T> ImmutableCollection<T> copyOf(Iterable<T> iterable) {
    if(iterable instanceof Set) {
        return ImmutableSet.copyOf(iterable);
    } else if(iterable instanceof Multiset) {
        return ImmutableMultiset.copyOf(iterable);
    } else {
        return ImmutableList.copyOf(iterable);
    }
}
 
Example 36
Project: googles-monorepo-demo   File: MediaType.java   View source code 5 votes vote down vote up
private Map<String, ImmutableMultiset<String>> parametersAsMap() {
  return Maps.transformValues(
      parameters.asMap(),
      new Function<Collection<String>, ImmutableMultiset<String>>() {
        @Override
        public ImmutableMultiset<String> apply(Collection<String> input) {
          return ImmutableMultiset.copyOf(input);
        }
      });
}
 
Example 37
Project: googles-monorepo-demo   File: NullPointerTesterTest.java   View source code 5 votes vote down vote up
@SuppressWarnings("unused") // called by NullPointerTester
public void checkDefaultValuesForTheseTypes(
    Gender gender,
    Integer integer, int i,
    String string, CharSequence charSequence,
    List<String> list,
    ImmutableList<Integer> immutableList,
    Map<String, Integer> map,
    ImmutableMap<String, String> immutableMap,
    Set<String> set,
    ImmutableSet<Integer> immutableSet,
    SortedSet<Number> sortedSet,
    ImmutableSortedSet<Number> immutableSortedSet,
    Multiset<String> multiset,
    ImmutableMultiset<Integer> immutableMultiset,
    Multimap<String, Integer> multimap,
    ImmutableMultimap<String, Integer> immutableMultimap,
    Table<String, Integer, Exception> table,
    ImmutableTable<Integer, String, Exception> immutableTable) {
  calledWith(
      gender,
      integer, i,
      string, charSequence,
      list, immutableList,
      map, immutableMap,
      set, immutableSet,
      sortedSet, immutableSortedSet,
      multiset, immutableMultiset,
      multimap, immutableMultimap,
      table, immutableTable);
}
 
Example 38
Project: googles-monorepo-demo   File: NullPointerTesterTest.java   View source code 5 votes vote down vote up
final void check() {
  runTester().assertNonNullValues(
      Gender.MALE,
      Integer.valueOf(0), 0,
      "", "",
      ImmutableList.of(), ImmutableList.of(),
      ImmutableMap.of(), ImmutableMap.of(),
      ImmutableSet.of(), ImmutableSet.of(),
      ImmutableSortedSet.of(), ImmutableSortedSet.of(),
      ImmutableMultiset.of(), ImmutableMultiset.of(),
      ImmutableMultimap.of(), ImmutableMultimap.of(),
      ImmutableTable.of(), ImmutableTable.of());
}
 
Example 39
Project: Mastering-Mesos   File: AttributeAggregateTest.java   View source code 5 votes vote down vote up
@Test
public void testNoTasks() {
  control.replay();

  AttributeAggregate aggregate = aggregate();
  assertEquals(ImmutableMultiset.<Pair<String, String>>of(), aggregate.getAggregates());
  assertAggregate(aggregate, "none", "alsoNone", 0);
}
 
Example 40
Project: Mastering-Mesos   File: AttributeAggregateTest.java   View source code 5 votes vote down vote up
@Test
public void testNoAttributes() {
  expectGetAttributes("hostA");

  control.replay();

  assertEquals(
      ImmutableMultiset.<Pair<String, String>>of(),
      aggregate(task("1", "hostA")).getAggregates());
}