数组过滤元素生成新数组

  public static <T> T[] filterArray(T[] resource, Predicate<T> filter, IntFunction<T[]> supplier) {
    
    


//        T[] o = ((T[]) Array.newInstance(resource[0].getClass(), 0));
        int count = 0;
        byte[] map = new byte[resource.length / 8 + 1];
        for (int i = 0; i < resource.length; i++) {
    
    
            if (filter.test(resource[i])) {
    
    
                map[i / 8] |= 1 << i % 8;
                count++;
            }
        }
        T[] res = supplier.apply(count);
        for (int i = 0, j = 0; i < resource.length && j < count; i++) {
    
    
            if ((map[i / 8] & 1 << i % 8) > 0) {
    
    
                res[j] = resource[i];
                j++;
            }

        }
        return res;

    }

    public static void main(String[] args) {
    
    
        for (String s : filterArray(new String[]{
    
    "a", "shit", "x", "shit","not shit"}, s -> !s.equals("shit"), value -> new String[value])) {
    
    

            System.err.println(s);
        }
    }

Guess you like

Origin blog.csdn.net/weixin_42002173/article/details/122491667