如果您愿意使用第三方库,您可以使用支持原始包的GS Collections。 Bag 是一种数据结构,用于跟踪每个唯一元素的出现。使用IntBag 可以减少您的用例所需的装箱量。
CharAdapter remove = CharAdapter.adapt("[]");
IntBag counts =
Lists.mutable.with("[1,2]", "[1,4]", "[4]", "[3,5]")
.asLazy()
.collectWith(StringIterate::rejectChar, remove::contains)
.flatCollect(StringIterate::csvTokensToList)
.collectInt(Integer::parseInt)
.toBag();
Assert.assertEquals(2, counts.occurrencesOf(1));
Assert.assertEquals(1, counts.occurrencesOf(2));
如果您需要按值排序的输出,您可以使用SortedBag<Integer> 代替。但是请注意,这将导致将整数装箱为整数。
CharAdapter remove = CharAdapter.adapt("[]");
SortedBag<Integer> counts =
Lists.mutable.with("[1,2]", "[1,4]", "[4]", "[3,5]")
.asLazy()
.collectWith(StringIterate::rejectChar, remove::contains)
.flatCollect(StringIterate::csvTokensToList)
.collect(Integer::parseInt)
.toSortedBag();
Assert.assertEquals(2, counts.occurrencesOf(1));
Assert.assertEquals(1, counts.occurrencesOf(2));
System.out.println(counts.toStringOfItemToCount());
输出:
{1=2, 2=1, 3=1, 4=2, 5=1}
注意:我是 GS Collections 的开发人员