代码之家  ›  专栏  ›  技术社区  ›  Tetsujin no Oni

为清晰起见,命名集合扩展

  •  5
  • Tetsujin no Oni  · 技术社区  · 17 年前

    static public List<T> filter(List<T> source, Predicate<T> filter);
    static <Y,T> public List<Y> transform(List<T> source, Mutator<Y,T> filter);
    static public boolean exists(List<T> source, Predicate<T> filter);
    static public T findFirst(List<T> source, Predicate<T> filter);
    static public boolean trueForAll(List<T> source, Predicate<T> filter);
    

    public interface Predicate<T> { public boolean apply(T item); }
    public interface Mutator<T,Y> { public Y apply(T item); }
    

    所以问题是:

    • 过滤器是包含扩展的类的好名字吗?如果没有,更好的?
    • 地图 变换 过滤器 ?
    • 我是否忘记在库类中包含任何重要的基于集合的函数?

    地图 变换 )是吗 地图 由于java.util.的多种用途,具有显著的语义负载。地图

    6 回复  |  直到 17 年前
        1
  •  1
  •   waxwing    17 年前

    有什么重要的集合吗 我忘了的功能 包括在图书馆课程中?

    对于高阶集合函数,我使用Adrian Kuhn在他的文章“ Pimp My Foreach ".

    其中一些你已经有了,但我还是想把它们扔出去:

    • 全部满意
    • 任何满意
    • 基数
    • 收集
    • 计数
    • 切割件
    • 检测
    • 折叠
    • 分组By
    • 索引
    • 注入
    • 拒绝
        2
  •  2
  •   cwash    17 年前

    我会给他们打电话 地图 过滤器

    我知道你并没有特别要求,但泛型方法中的一些签名可以改进:

     static public <T> List<T> filter(List<T> source, Predicate<? super T> filter);
     static public <Y,T> List<Y> transform(List<T> source, Mutator<Y,? super T> filter);
     static public <T> boolean exists(List<T> source, Predicate<? super T> filter);
     static public <T> T findFirst(List<T> source, Predicate<? super T> filter);
     static public <T> boolean trueForAll(List<T> source, Predicate<? super T> filter);
    
        3
  •  1
  •   Paul Sonier    17 年前

    这看起来真的很漂亮;我认为你肯定在正确的轨道上。是的,我觉得穆塔托是个好名字;transform更好,因为它更常被解读为动词,而map具有可能令人困惑的“名词”内涵;我认为你可能想要的唯一一个主要的基于集合的函数是重新排序函数。

        4
  •  1
  •   dfa    17 年前

    在我使用过的一个类似的图书馆里:

    • 规格说明 代替 谓词 : aSpecification.isSatisfiedBy(anObject);
    • 代替 突变器
    • 地图 收集 对于闲聊者( 变换 在你的情况下)
    • 折叠 注入 对于闲聊者
    • 过滤器 选择 对于闲聊者
        5
  •  0
  •   Carl Manaster    17 年前

    这不是你真正问的,但这符合你问题的精神。对我来说,最好说:

    List<String> shortWords = filtered(allWords, short);
    

    List<String> shortWords = filter(allWords, short);
    

    我会坚持下去 变换 过滤器 .

        6
  •  0
  •   alphazero    17 年前

    为了保持一致性,Transform应该是Mutate(或者Mutator应该是Transformer)。这似乎相当清楚其意图:

    static <Y,T> public List<Y> mutate (List<T> originalForm, Mutator<Y,T> mutator);
    

    规范也有点冗长(但更一致和传统):

    static public boolean isTrueForAll(List<T> source, Predicate<T> filter);
    

    static public boolean assertTrueForAll(List<T> source, Predicate<T> filter);