• Skip to primary navigation
  • Skip to content

Luc Russell

Data Engineering and Full Stack Development

  • Home
  • Blog

Java Collections Quick Reference

03/21/2015 by Luc

A cheat sheet for my frequently used/forgotten Java Collections snippets.

Quickly Create a List

1
2
3
4
import static java.util.Arrays.asList;
asList("hello", "goodbye");
import static java.util.Collections.unmodifiableList;
unmodifiableList(asList("hello", "goodbye"));

Empty Collection Syntax

1
List<String> requiredInputs = Collections.<String>emptyList();

Also see here.

Safe Empty Array

1
2
3
public static String[] safe(String[] other ) {
    return other == null ? new String[0] : other;
}

Convert Array to List

1
Arrays.asList(values)

Collection to Array

1
values.toArray(new String[values.size()])

Loop Over Keys And Values In A Map

1
2
3
4
5
6
for (Iterator<Map.Entry<String, Object>> it = resultsData.entrySet().iterator(); it.hasNext();) {
            Map.Entry<String, Object> entry = it.next();
            String key = entry.getKey();
            Object value = entry.getValue();
            System.out.println(String.format("key: %s, value: %s", key, value));
        }

Filed Under: code snippets, quick reference Tagged With: collections, java

Convert a Collection to Another Type With Commons Collections

06/19/2013 by Luc

1
2
3
4
5
6
7
8
9
10
11
12
private Collection<Apple> convert(final Collection<Orange> values) {
    final Collection<Apple> converted = CollectionUtils.collect(values, new Transformer(){
      public Object transform(final Object target){
        Orange result = null;
        if(target != null){
            result = new Apple(target.getName());
        }
        return result;
      }
    });
    return converted;
}

Filed Under: code snippets Tagged With: collections, java

How To Select Elements From a Collection With Apache Commons Collections

06/18/2013 by Luc

1
2
3
4
5
6
7
8
9
10
11
private List<Vegetable> getVegetablesLike(List<Vegetable> allVegetables,
                final Vegetable vegetable) {
    return (List<Vegetable>)
        select(allVegetables, new Predicate() {
        @Override
        public boolean evaluate(Object o) {
            Vegetable other = (Vegetable) o;
            return other.equals(vegetable);
        }
    });
}

Filed Under: code snippets Tagged With: collections, java

Copyright ©2019 Luc Russell | Site by Sproutee