Eclipse Collections的API设计演进


Eclipse Collections是一个开源Java集合框架,可以用Java编写功能齐全,流畅的代码,这篇文章解释了成熟Java集合库的演化策略:

历史
Eclipse Collections于2004年在Goldman Sachs开始作为一个名为Caramel的集合框架开始,在2012年,它作为一个名为GS Collections的项目开放给GitHub。多年来,大约40名来自同一公司的开发人员为集合框架做出了贡献。为了最大限度地发挥开源项目的最佳性质,GS Collections被迁移到Eclipse Foundation,在2015年重新命名为Eclipse Collections。现在该框架对社区完全开放,接受贡献!

设计目标
Eclipse Collections旨在提供丰富,功能,流畅和有趣的API以及内存高效的数据结构,同时提供与Java Collections的互操作性。它提供了缺失的类型,如Bag,Multimap,Stack,BiMap,Interval。

框架的演变
在过去14年多的时间里,框架已经成熟,最高接口:RichIterable现在有超过100种方法。经过仔细考虑后,这些方法被包含在接口中。

比如让我们在Eclipse Collections版本9.0.0中添加的简单API,实现一个RichIterablecountBy() :

MutableList<String> strings = Lists.mutable.with(
        "1", "2", "2", "3", "3", "3", "4", "4", "4", "4");
Bag<Integer> integers = strings.collect(
        Integer::valueOf, 
        Bags.mutable.empty());
Assert.assertEquals(1, integers.occurrencesOf(1));
Assert.assertEquals(2, integers.occurrencesOf(2));
Assert.assertEquals(3, integers.occurrencesOf(3));
Assert.assertEquals(4, integers.occurrencesOf(4));


上面计算整数的解决方案是有效的,但是,它并不直观。没有经验的开发人员可能很难实现此解决方案。因此,我们决定添加countBy(),现在代码看起来更实用,更流畅,更直观。

MutableList<String> strings = Lists.mutable.with(
        "1", "2", "2", "3", "3", "3", "4", "4", "4", "4");
Bag<Integer> integers = strings.countBy(Integer::valueOf);
Assert.assertEquals(1, integers.occurrencesOf(1));
Assert.assertEquals(2, integers.occurrencesOf(2));
Assert.assertEquals(3, integers.occurrencesOf(3));
Assert.assertEquals(4, integers.occurrencesOf(4));

GitHub项目