As Tim Biegeleisen said, here's an approach if you're using Java 8:
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.*;
public class CollectByLength {
public static void main(String[] args) {
Map<Integer, List<String>> map = Stream.of("apple", "orange", "car", "can", "fuzzy")
.collect(groupingBy(String::length));
System.out.println(map); //prints {3=[car, can], 5=[apple, fuzzy], 6=[orange]}
}
}
If you care about the List implementation for some reason, the above solution doesn't provide any guarantee on the list implementation. From the doc:
There are no guarantees on the type, mutability, serializability, or
thread-safety of the Map or List objects returned.
But it's also possible to specify the List implementation you need (LinkedList here)
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import static java.util.stream.Collectors.*;
public class CollectByLength {
public static void main(String[] args) {
Map<Integer, List<String>> map = Stream.of("apple", "orange", "car", "can", "fuzzy")
.collect(groupingBy(String::length, toCollection(LinkedList::new)));
System.out.println(map); //prints {3=[car, can], 5=[apple, fuzzy], 6=[orange]}
}
}