All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.boon.Lists Maven / Gradle / Ivy

Go to download

Simple opinionated Java for the novice to expert level Java Programmer. Low Ceremony. High Productivity. A real boon to Java to developers!

There is a newer version: 0.34
Show newest version
/*
 * Copyright 2013-2014 Richard M. Hightower
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  		http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * __________                              _____          __   .__
 * \______   \ ____   ____   ____   /\    /     \ _____  |  | _|__| ____    ____
 *  |    |  _//  _ \ /  _ \ /    \  \/   /  \ /  \\__  \ |  |/ /  |/    \  / ___\
 *  |    |   (  <_> |  <_> )   |  \ /\  /    Y    \/ __ \|    <|  |   |  \/ /_/  >
 *  |______  /\____/ \____/|___|  / \/  \____|__  (____  /__|_ \__|___|  /\___  /
 *         \/                   \/              \/     \/     \/       \//_____/
 *      ____.                     ___________   _____    ______________.___.
 *     |    |____ ___  _______    \_   _____/  /  _  \  /   _____/\__  |   |
 *     |    \__  \\  \/ /\__  \    |    __)_  /  /_\  \ \_____  \  /   |   |
 * /\__|    |/ __ \\   /  / __ \_  |        \/    |    \/        \ \____   |
 * \________(____  /\_/  (____  / /_______  /\____|__  /_______  / / ______|
 *               \/           \/          \/         \/        \/  \/
 */

package org.boon;


import org.boon.collections.DoubleList;
import org.boon.collections.FloatList;
import org.boon.collections.IntList;
import org.boon.collections.LongList;
import org.boon.core.*;
import org.boon.core.reflection.*;
import org.boon.core.reflection.fields.FieldAccess;
import org.boon.primitive.CharBuf;

import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;


public class Lists {


    public static  List lazyAdd(List list, T... items) {
        list = list == null ? new ArrayList() : list;

        for (T item : items) {
            list.add(item);
        }
        return list;
    }


    public static  List lazyAdd(ArrayList list, T... items) {
        list = list == null ? new ArrayList() : list;

        for (T item : items) {
            list.add(item);
        }
        return list;    }

    public static  List safeLazyAdd(CopyOnWriteArrayList list, T... items) {
        list = list == null ? new CopyOnWriteArrayList() : list;
        for (T item : items) {
            list.add(item);
        }
        return list;
    }

    public static  List lazyAdd(CopyOnWriteArrayList list, T... items) {
        list = list == null ? new CopyOnWriteArrayList() : list;
        for (T item : items) {
            list.add(item);
        }
        return list;
    }




    public static  List lazyCreate(List list) {
        return list == null ? new ArrayList() : list;
    }



    public static  List lazyCreate(ArrayList list) {
        return list == null ? new ArrayList() : list;
    }


    public static  List lazyCreate(CopyOnWriteArrayList list) {
        return list == null ? new CopyOnWriteArrayList() : list;
    }


    public static  List safeLazyCreate(CopyOnWriteArrayList list) {
        return list == null ? new CopyOnWriteArrayList() : list;
    }

    public static  T fromList( List list, Class clazz ) {
        return MapObjectConversion.fromList( list, clazz );
    }

    public static  List list( Class clazz ) {
        return new ArrayList<>();
    }


    public static  List copy( Collection collection ) {
        return new ArrayList<>( collection );
    }


    public static  List deepCopy( Collection collection ) {
        List list = new ArrayList<>(collection.size());

        for (V v : collection) {
            list.add( BeanUtils.copy( v ));
        }
        return list;
    }

    public static  List deepCopyToList( Collection src,  List dst) {

        for (V v : src) {
            dst.add( BeanUtils.copy( v ));
        }
        return  dst;
    }


    public static  List deepCopy( Collection src, Class dest  ) {
        List list = new ArrayList<>(src.size());

        for (V v : src) {
            list.add( BeanUtils.createFromSrc( v, dest ));
        }
        return list;
    }

    /**
     * Clones each list item into a new instance with copied fields.
     * It is like doing a clone operation.
     *
     * If the passed list is a LinkedList then the returned list will be a
     * LinkedList.
     *
     * If the passed list is a CopyOnWriteArrayList then the returned list will
     * be a CopyOnWriteArrayList list.
     *
     * All other lists become ArrayList.
     *
     * @param list list to clone
     * @param  generics
     * @return new list
     */
    @Universal
    public static  List deepCopy( List list ) {
        if ( list instanceof LinkedList ) {
            return deepCopyToList( list, new LinkedList(  ) );
        } else if ( list instanceof CopyOnWriteArrayList ) {
            return deepCopyToList( list, new CopyOnWriteArrayList(  ));
        } else {
            return deepCopy( (Collection)list);
        }
    }


    public static  List> lists( Collection... collections ) {
        List> lists = new ArrayList<>(collections.length);
        for (Collection collection : collections) {
            lists.add(new ArrayList<>(collection));
        }
        return lists;
    }



    public static  List list( Iterable iterable ) {
        List list = new ArrayList<>();
        for ( V o : iterable ) {
            list.add( o );
        }
        return list;
    }



    public static  List list( Collection collection ) {
        return new ArrayList<>(collection);
    }

    public static  List linkedList( Iterable iterable ) {
        List list = new LinkedList<>();
        for ( V o : iterable ) {
            list.add( o );
        }
        return list;
    }

    public static List toListOrSingletonList( Object item ) {
        if ( item == null ) {
            return new ArrayList<>();
        } else if ( item.getClass().isArray() ) {
            final int length = Array.getLength( item );
            List list = new ArrayList<>();
            for ( int index = 0; index < length; index++ ) {
                list.add( Array.get( item, index ) );
            }
            return list;
        } else if ( item instanceof Collection ) {
            return list( ( Collection ) item );
        } else if ( item instanceof Iterator ) {
            return list( ( Iterator ) item );
        } else if ( item instanceof Enumeration ) {
            return list( ( Enumeration ) item );
        } else if ( item instanceof Iterable ) {
            return list( ( Iterable ) item );
        } else {
            List list = new ArrayList<>();
            list.add( item );
            return list;
        }
    }


    public static  List toList( List inputList, Class cls, String propertyPath ) {
        List outputList = new ArrayList<>();

        for (Object o : inputList) {
            outputList.add((PROP) BeanUtils.idx(o, propertyPath));
        }

        return outputList;
    }

    public static IntList toIntList( List inputList, String propertyPath ) {

        return IntList.toIntList(inputList, propertyPath);
    }


    public static FloatList toFloatList( List inputList, String propertyPath ) {

        return FloatList.toFloatList(inputList, propertyPath);
    }


    public static DoubleList toDoubleList( List inputList, String propertyPath ) {

        return DoubleList.toDoubleList(inputList, propertyPath);
    }


    public static LongList toLongList( List inputList, String propertyPath ) {

        return LongList.toLongList(inputList, propertyPath);
    }

    public static List toList( List inputList, String propertyPath ) {
        List outputList = new ArrayList<>();

        for (Object o : inputList) {
            outputList.add(BeanUtils.idx(o, propertyPath));
        }

        return outputList;
    }

    public static List toList( Object item ) {
       if ( item!= null && item.getClass().isArray() ) {
            final int length = Array.getLength( item );
            List list = new ArrayList<>();
            for ( int index = 0; index < length; index++ ) {
                list.add( Array.get( item, index ) );
            }
            return list;
        } else if ( item instanceof Collection ) {
            return list( ( Collection ) item );
        } else if ( item instanceof Iterator ) {
            return list( ( Iterator ) item );
        } else if ( item instanceof Enumeration ) {
            return list( ( Enumeration ) item );
        } else if ( item instanceof Iterable ) {
            return list( ( Iterable ) item );
        } else {
            return MapObjectConversion.toList( item );
        }
    }



    public static  List convert(Class wrapper, Iterable collection ) {
        List list = new ArrayList<>(  );

        for (V v : collection) {

            list.add ( Conversions.coerce(wrapper, v) );
        }
        return list;
    }

    public static  List convert(Class wrapper, Collection collection ) {
        List list = new ArrayList<>( collection.size() );

        for (V v : collection) {

            list.add ( Conversions.coerce(wrapper, v) );
        }
        return list;
    }


    public static  List convert(Class wrapper, V[] collection ) {
        List list = new ArrayList<>( collection.length );

        for (V v : collection) {

            list.add ( Conversions.coerce(wrapper, v) );
        }
        return list;
    }


    public static  List wrap(Class wrapper, Iterable collection ) {
        List list = new ArrayList<>(  );

        for (V v : collection) {
            WRAP wrap = Reflection.newInstance ( wrapper, v );
            list.add ( wrap );
        }
        return list;
    }

    public static  List wrap(Class wrapper, Collection collection ) {

        if (collection.size()==0) {
            return Collections.EMPTY_LIST;
        }

        List list = new ArrayList<>( collection.size () );



        ClassMeta  cls = ClassMeta.classMeta(wrapper);
        ConstructorAccess declaredConstructor = cls.declaredConstructor(collection.iterator().next().getClass());

        for (V v : collection) {
            WRAP wrap = declaredConstructor.create (  v );
            list.add ( wrap );
        }
        return list;
    }


    public static  List wrap(Class wrapper, V[] collection ) {
        List list = new ArrayList<>( collection.length );

        for (V v : collection) {
            WRAP wrap = Reflection.newInstance ( wrapper, v );
            list.add ( wrap );
        }
        return list;
    }

    public static  List list( Enumeration enumeration ) {
        List list = new ArrayList<>();
        while ( enumeration.hasMoreElements() ) {
            list.add( enumeration.nextElement() );
        }
        return list;
    }


    public static  Enumeration enumeration( final List list ) {
        final Iterator iter = list.iterator();
        return new Enumeration() {
            @Override
            public boolean hasMoreElements() {
                return iter.hasNext();
            }

            @Override
            public V nextElement() {
                return iter.next();
            }
        };

    }


    public static  List list( Iterator iterator ) {
        List list = new ArrayList<>();
        while ( iterator.hasNext() ) {
            list.add( iterator.next() );
        }
        return list;
    }



    @SafeVarargs
    public static  List list( final V... array ) {
        if ( array == null ) {
            return new ArrayList<>();
        }
        List list = new ArrayList<>( array.length );
        Collections.addAll( list, array );
        return list;
    }

    public static  List safeList(Class cls) {
        return new CopyOnWriteArrayList<>(  );
    }

    @SafeVarargs
    public static  List safeList( final V... array ) {
        return new CopyOnWriteArrayList<>( array );
    }

    @SafeVarargs
    public static  List linkedList( final V... array ) {
        if ( array == null ) {
            return new LinkedList<>();
        }
        List list = new LinkedList<>();
        Collections.addAll( list, array );
        return list;
    }


    public static  List safeList( Collection collection ) {
        return new CopyOnWriteArrayList<>( collection );
    }

    public static  List linkedList( Collection collection ) {
        return new LinkedList<>( collection );
    }

    /**
     * Universal methods
     */
    @Universal
    public static int len( List list ) {
        return list.size();
    }


    @Universal
    public static int lengthOf( List list ) {
        return len (list);
    }

    public static boolean isEmpty( List list ) {
        return list == null || list.size() == 0;
    }

    @Universal
    public static  boolean in( V value, List list ) {
        return list.contains( value );
    }

    @Universal
    public static  void add( List list, V value ) {
        list.add( value );
    }


    @Universal
    public static  void add( List list, V... values ) {
        for (V v : values) {
            list.add( v );
        }
    }

    @Universal
    public static  T atIndex( List list, final int index ) {

        return idx(list, index);

    }

    @Universal
    public static  T idx( List list, final int index ) {
        int i = calculateIndex( list, index );
        if ( i > list.size() - 1 ) {
            i = list.size() - 1;
        }
        return list.get( i );

    }

    public static  List idxList( List list, final int index ) {
        return (List) idx(list, index);
    }


    public static  Map idxMap( List list, final int index ) {
        return (Map) idx(list, index);
    }


    @Universal
    public static  void atIndex( List list, int index, V v ) {
        idx (list, index, v);
    }

    @Universal
    public static  void idx( List list, int index, V v ) {
        int i = calculateIndex( list, index );
        list.set( i, v );
    }


    @Universal
    public static  List sliceOf( List list, int startIndex, int endIndex ) {
        return slc(list, startIndex, endIndex);
    }

    @Universal
    public static  List slc( List list, int startIndex, int endIndex ) {
        int start = calculateIndex( list, startIndex );
        int end = calculateIndex( list, endIndex );
        return list.subList( start, end );
    }


    @Universal
    public static  List sliceOf( List list, int startIndex ) {
        return slc(list, startIndex);
    }

    @Universal
    public static  List slc( List list, int startIndex ) {
        return slc( list, startIndex, list.size() );
    }

    @Universal
    public static  List endSliceOf( List list, int endIndex ) {
        return slcEnd( list, endIndex );
    }


    @Universal
    public static  List slcEnd( List list, int endIndex ) {
        return slc( list, 0, endIndex );
    }


    @Universal
    public static  List copy( List list ) {
        if ( list instanceof LinkedList ) {
            return new LinkedList<>( list );
        } else if ( list instanceof CopyOnWriteArrayList ) {
            return new CopyOnWriteArrayList<>( list );
        } else {
            return new ArrayList<>( list );
        }
    }


    @Universal
    public static  List copy( CopyOnWriteArrayList list ) {
        return new CopyOnWriteArrayList<>( list );
    }

    @Universal
    public static  List copy( ArrayList list ) {
        return new ArrayList<>( list );
    }

    @Universal
    public static  List copy( LinkedList list ) {
        return new LinkedList<>( list );
    }


    @Universal
    public static  void insert( List list, int index, V v ) {
        int i = calculateIndex( list, index );
        list.add( i, v );
    }


    /* End universal methods. */
    private static  int calculateIndex( List list, int originalIndex ) {
        final int length = list.size();

        int index = originalIndex;

        /* Adjust for reading from the right as in
        -1 reads the 4th element if the length is 5
         */
        if ( index < 0 ) {
            index = ( length + index );
        }


        /* Bounds check
            if it is still less than 0, then they
            have an negative index that is greater than length
         */
        if ( index < 0 ) {
            index = 0;
        }
        if ( index > length ) {
            index = length;
        }
        return index;
    }


    public static  List listFromProperty( Class propertyType, String propertyPath, Collection list ) {
        List newList = new ArrayList<>( list.size() );

        for ( Object item : list ) {
            T newItem = ( T ) BeanUtils.idx( item, propertyPath );
            newList.add( newItem );
        }

        return newList;

    }


    public static  List listFromProperty( Class propertyType, String propertyPath, Iterable list ) {
        List newList = new ArrayList<>(  );

        for ( Object item : list ) {
            T newItem = ( T ) BeanUtils.idx( item, propertyPath );
            newList.add( newItem );
        }

        return newList;

    }
    public static List> toListOfMaps( List list ) {
        return MapObjectConversion.toListOfMaps( list );
    }

    public static void setListProperty(List list, String propertyName, Object value) {
        for (Object object : list) {
            BeanUtils.idx(object, propertyName, value);
        }
    }


    public static List mapBy( Object[] objects, Object instance, String methodName) {

        List list = new ArrayList(objects.length);
        for (Object o : objects) {
            list.add( Invoker.invoke(instance, methodName, o ));
        }
        return list;
    }


    public static List mapBy(Object[] objects, Class cls, String methodName) {

        List list = new ArrayList(objects.length);
        for (Object o : objects) {
            list.add( Invoker.invoke(cls,methodName, o ));
        }
        return list;
    }



    public static List mapBy(Iterable objects, Class cls, String methodName) {

        List list = new ArrayList();
        for (Object o : objects) {
            list.add( Invoker.invoke(cls, methodName, o ));
        }
        return list;
    }


    public static List mapBy(Iterable objects, Object instance, String methodName) {

        List list = new ArrayList();
        for (Object o : objects) {
            list.add( Invoker.invoke(instance, methodName, o ));
        }
        return list;
    }


    public static List mapBy(Collection objects, Class cls, String methodName) {

        List list = new ArrayList(objects.size());

        MethodAccess methodAccess = Invoker.invokeMethodAccess(cls, methodName);

        for (Object o : objects) {
            list.add( methodAccess.invokeStatic(o));
        }
        return list;
    }

    public static List mapBy(Collection objects, Object function) {


            MethodAccess methodAccess = Invoker.invokeFunctionMethodAccess(function);

            List list = new ArrayList();
            for (Object o : objects) {
                list.add( methodAccess.invoke(function, o));
            }

            return list;
    }


    public static  List mapBy(Class cls, Collection objects, Object function) {
        return (List) mapBy(objects, function);
    }

    public static List mapBy(Iterable objects, Object function) {


        MethodAccess methodAccess = Invoker.invokeFunctionMethodAccess(function);

        List list = new ArrayList();
        for (Object o : objects) {
            list.add( methodAccess.invoke(function, o));
        }
        return list;
    }


    public static List mapBy(Object[] objects, Object function) {

        MethodAccess methodAccess = Invoker.invokeFunctionMethodAccess(function);

        List list = new ArrayList(objects.length);
        for (Object o : objects) {
            list.add( methodAccess.invoke(function, o));
        }
        return list;
    }



     public static List mapBy(Collection objects, Object object, String methodName) {


         MethodAccess methodAccess = Invoker.invokeMethodAccess(object.getClass(), methodName);

        List list = new ArrayList(objects.size());
        for (Object o : objects) {
            list.add( methodAccess.invoke(object, o));
        }
        return list;
    }


    public static  List mapBy(  final V[] array, Function function ) {
        List list = new ArrayList<>( array.length );

        for ( V v : array ) {
            list.add( function.apply( v ) );
        }
        return list;
    }

    public static  List mapBy( final Collection array, Function function ) {
        List list = new ArrayList<>( array.size() );

        for ( V v : array ) {
            list.add( function.apply( v ) );
        }
        return list;
    }

    public static  List mapBy( final Iterable array, Function function ) {
        List list = new ArrayList<>(  );

        for ( V v : array ) {
            list.add( function.apply( v ) );
        }
        return list;
    }


    public static  SUM reduceBy( final Iterable array, Reducer function ) {

        SUM sum = null;
        for ( V v : array ) {
            sum = function.apply( sum, v ) ;
        }
        return sum;
    }


    public static Object reduceBy( final Iterable array, Object object ) {

        Object sum = null;
        for ( Object v : array ) {
            sum = Invoker.invokeReducer(object, sum, v);
        }
        return sum;
    }



    public static  List filterBy( final Iterable array, Predicate predicate ) {
        List list = new ArrayList<>(  );

        for ( T v : array ) {
            if ( predicate.test(v)) {
                list.add(  v  );
            }
        }
        return list;
    }


    public static  List filterBy(  final Collection array, Predicate predicate ) {
        List list = new ArrayList<>( array.size()  );

        for ( T v : array ) {
            if ( predicate.test(v)) {
                list.add(  v  );
            }
        }
        return list;
    }


    public static  List filterBy( Predicate predicate, final T[] array ) {
        List list = new ArrayList<>( array.length  );

        for ( T v : array ) {
            if ( predicate.test(v)) {
                list.add(  v  );
            }
        }
        return list;
    }



    public static  List filterBy(  final Iterable array, Object object ) {
        List list = new ArrayList<>(  );

        for ( T v : array ) {
            if ( Invoker.invokeBooleanReturn(object, v) ) {
                list.add(  v  );
            }
        }
        return list;
    }


    public static  List filterBy( final Collection array, Object object ) {
        List list = new ArrayList<>( array.size()  );

        for ( T v : array ) {
            if ( Invoker.invokeBooleanReturn(object, v) ) {
                list.add(  v  );
            }
        }
        return list;
    }


    public static  List filterBy(  final T[] array, Object object ) {
        List list = new ArrayList<>( array.length  );

        for ( T v : array ) {
            if ( Invoker.invokeBooleanReturn(object, v) ) {
                list.add(  v  );
            }
        }
        return list;
    }




    public static  List filterBy(  final Iterable array, Object object, String methodName ) {
        List list = new ArrayList<>(  );

        for ( T v : array ) {
            if ( (boolean) Invoker.invokeEither(object, methodName, v) ) {
                list.add(  v  );
            }
        }
        return list;
    }


    public static  List filterBy( final Collection array, Object object, String methodName ) {
        List list = new ArrayList<>( array.size()  );

        for ( T v : array ) {
            if ( (boolean) Invoker.invokeEither(object, methodName, v) ) {
                list.add(  v  );
            }
        }
        return list;
    }


    public static  List filterBy(  final T[] array, Object object, String methodName ) {
        List list = new ArrayList<>( array.length  );

        for ( T v : array ) {
            if ( (boolean) Invoker.invokeEither(object, methodName, v) ) {
                list.add(  v  );
            }
        }
        return list;
    }



    public static String toPrettyJson(List list) {
        CharBuf buf = CharBuf.createCharBuf();
        return buf.prettyPrintCollection(list, false, 0).toString();
    }
}