Table of Contents

Java - List (sequence)

About

A list (also known as a sequence):

A special iterator, called a ListIterator, allows element insertion and replacement, and bidirectional access (from begin or from end) in addition to the normal operations.

Interface and Implementation

List is an interface from the Java Collections Framework representing an ordered collection (also known as a sequence).

See List for all implementations. The most known is the ArrayList: a Resizable-array that permits all elements, including null.

Management

Instantiation

From Array

From an array

List<Class> myList = new ArrayList<Class>();

// With String as Class
List<String> messages = new java.util.ArrayList(Arrays.asList("Nico", "Gerard"));

// The java.util.ArrayList transform the list implementation of the return list from Arrays.asList

See asList

public static <T> List<T> asList(T... object) {
    return Arrays.stream(object)
      .collect(Collectors.toList());
}

New Operator

List<Class> myList = new ArrayList<Class>();

The ArrayList(int) constructor gives a List that has size 0. It only ensures that n elements can be added before it needs to reallocate the underlying array.

From scalar

Collections.singletonList(myObject)

Concatenation

List<String> list = new ArrayList<String>();
newList.addAll(secondList);

Join

String join = String.join("joinSeparator", list);
final String headers = columns.stream()
                .map(s->s.getColumnName())
                .collect(Collectors.joining(","));

Copy

The element are not copied.

List<String> copyList = new ArrayList<String>();
copyList.addAll(list);

Deep Copy

The element are also copied.

for(Object obj:list){
    copyList.add(obj.clone());
    copyList.add(obj.clone());
}

Cast

List<B> variable = (List<B>)(List<?>) collectionOfListA;

Sort

foreignKeys = foreignKeys.stream()
                .sorted((s1,s2)->(s1.getForeignPrimaryKey().getTableDef().getName()).compareTo(s2.getForeignPrimaryKey().getTableDef().getName()))
                .collect(Collectors.toList());
// same as
foreignKeys = foreignKeys.stream()
                .sorted(Comparator.comparing(s -> (s.getForeignPrimaryKey().getTableDef().getName())))
                .collect(Collectors.toList());
foreignKeys = foreignKeys.stream()
                .sorted((s1,s2)->(s2.getForeignPrimaryKey().getTableDef().getName()).compareTo(s1.getForeignPrimaryKey().getTableDef().getName()))
                .collect(Collectors.toList());
// same as
foreignKeys = foreignKeys.stream()
                .sorted(Comparator.comparing(s -> (s.getForeignPrimaryKey().getTableDef().getName())).reversed())
                .collect(Collectors.toList());

Reverse

List<String> elements  = elements.stream()
   .sorted(Collections.reverseOrder())
   .collect(Collectors.toList());
Collections.reverse() 

Stream to

Stream

toList

List<Person> persons = new ArrayList<>();
// ... add persons
List<String> names = persons.stream()
                .map(a -> a.getName())
                .collect(Collectors.toCollection(ArrayList::new));
                
// or 
//     .collect(Collectors.toList());
List<String> groups =
	properties.stream()
	.flatMap(x->x.getListOfStrings().stream())
	.collect(Collectors.toList());

toMap

List<Person> persons = new ArrayList<>();
// ... add persons
Map<Integer, CliWord> personsMap = persons.stream()
                .filter(p -> p.getNummer()!=null)
                .collect(Collectors.toMap(Person::getNummer, Function.identity()));
List<String> persons = new ArrayList<>();
Map<String, String> personsMap = persons.stream()
            .collect(Collectors.toMap(
                s -> s, 
                s -> lookupFirstName(s)
            ));
Map<String, List<Person>> groupedByName = persons
        .stream()
        .collect(Collectors.groupingBy(Person::getName));
Map<T, Double> buckets = genericList
        .stream()
        .collect(Collectors.toMap(
          g->g,
          g->1.0
        ));

toArray

List to array

list.toArray(new Class[0])
// before version I don't know anymore
list.toArray(new Class[arraySize])
// For a list of string
list.toArray(new String[5])
// since opendJdk java 6 better not to pre-size
list.toArray(new String[0])

// Example
List<String> myList = new ArrayList<>();
myList.add("first");
myList.add("second");

String[] myArray = myList.toArray(new String[myList.size()])
// from Stream
final String[] nativeColumns = foreignKeyDef.getNativeColumns().stream()
                        .map(ColumnDef::getColumnName)
                        .toArray(String[]::new);

toGenericArray

// Based on
T[] arrayGeneric = (T[]) Array.newInstance(clazz,size)

// With Stream
T[] objects = valuesList.stream()
        .map(o -> Casts.cast(o, columnDef.getClazz()))
        .collect(Collectors.toList())
        .toArray((T[]) Array.newInstance(clazz,0));

ToSet

mySet = new HashSet<>(list);

Documentation / Reference