Java常用工具类之ArrayUtil

过滤

ArrayUtil.filter方法用于编辑已有数组元素,只针对泛型数组操作,原始类型数组并未提供。 方法中Editor接口用于返回每个元素编辑后的值,返回null此元素将被抛弃。

例如:过滤数组,只保留偶数

Integer[] a = {1,2,3,4,5,6};
Integer[] filter = ArrayUtil.filter(a, new Editor<Integer>(){
    @Override
    public Integer edit(Integer t) {
        return (t % 2 == 0) ? t : null
    }});
Assert.assertArrayEquals(filter, new Integer[]{2,4,6});

//其中,ArrayUtil.filter() 传递了一个匿名内部类,在大括号里面进行方法的实现。

 

 

其中:

filter 方法

/**
     * 过滤
     * 
     * @param <T> 数组元素类型
     * @param array 数组
     * @param editor 编辑器接口
     * @return 过滤后的数组
     */
    public static <T> T[] filter(T[] array, Editor<T> editor) {
        ArrayList<T> list = new ArrayList<T>();
        T modified;
        for (T t : array) {
            modified = editor.edit(t);
            if (null != modified) {
                list.add(t);
            }
        }
        return list.toArray(Arrays.copyOf(array, list.size()));
    }

 

Editor 接口:
/**
 * 编辑器接口,常用于对于集合中的元素做统一编辑<br>
 * 此编辑器两个作用:
 * 
 * <pre>
 * 1、如果返回值为<code>null</code>,表示此值被抛弃 
 * 2、对对象做修改
 * </pre>
 * 
 * @param <T> 被编辑对象类型
 * @author Looly
 */
public interface Editor<T> {
    /**
     * 修改过滤后的结果
     * 
     * @param t 被过滤的对象
     * @return 修改后的对象,如果被过滤返回<code>null</code>
     */
    public T edit(T t);
}

 

posted @ 2017-11-05 16:11  Mr_伍先生  阅读(1879)  评论(0编辑  收藏  举报