Java常用工具類之ArrayUtil

來源:互聯網
上載者:User

標籤:filter   code   匿名內部類   integer   物件類型   集合   傳回值   ann   edit   

過濾

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);}

 

Java常用工具類之ArrayUtil

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.