Java 与 Kotlin 中的集合
Collections are groups of a variable number of items (possibly zero) that are significant to the problem being solved and are commonly operated on. This guide explains and compares collection concepts and operations in Java and Kotlin. It will help you migrate from Java to Kotlin and write your code in the authentically Kotlin way.
The first part of this guide contains a quick glossary of operations on the same collections in Java and Kotlin. It is divided into operations that are the same and operations that exist only in Kotlin. The second part of the guide, starting from Mutability, explains some of the differences by looking at specific cases.
For an introduction to collections, see the Collections overview or watch this video by Sebastian Aigner, Kotlin Developer Advocate.
All of the examples below use Java and Kotlin standard library APIs only.
在 Java 与 Kotlin 中相同的操作
In Kotlin, there are many operations on collections that look exactly the same as their counterparts in Java.
对 list、 set、 queue 与 deque 的操作
描述 | 共有操作 | 更多 Kotlin 替代方式 |
---|---|---|
Add an element or elements | add() , addAll() | Use the plusAssign(+=) operator: collection += element , collection += anotherCollection . |
Check whether a collection contains an element or elements | contains() , containsAll() | Use the in keyword to call contains() in the operator form: element in collection . |
Check whether a collection is empty | isEmpty() | Use isNotEmpty() to check whether a collection is not empty. |
Remove under a certain condition | removeIf() | |
Leave only selected elements | retainAll() | |
Remove all elements from a collection | clear() | |
Get a stream from a collection | stream() | Kotlin has its own way to process streams: sequences and methods like map() and filter(). |
Get an iterator from a collection | iterator() |
对 map 的操作
描述 | 共有操作 | 更多 Kotlin 替代方式 |
---|---|---|
Add an element or elements | put() , putAll() , putIfAbsent() | In Kotlin, the assignment map[key] = value behaves the same as put(key, value) . Also, you may use the plusAssign(+=) operator: map += Pair(key, value) or map += anotherMap . |
Replace an element or elements | put() , replace() , replaceAll() | Use the indexing operator map[key] = value instead of put() and replace() . |
Get an element | get() | Use the indexing operator to get an element: map[index] . |
Check whether a map contains an element or elements | containsKey() , containsValue() | Use the in keyword to call contains() in the operator form: element in map . |
Check whether a map is empty | isEmpty() | Use isNotEmpty() to check whether a map is not empty. |
Remove an element | remove(key) , remove(key, value) | Use the minusAssign(-=) operator: map -= key . |
Remove all elements from a map | clear() | |
Get a stream from a map | stream() on entries, keys, or values |
仅针对 list 的操作
描述 | 共有操作 | 更多 Kotlin 替代方式 |
---|---|---|
Get an index of an element | indexOf() | |
Get the last index of an element | lastIndexOf() | |
Get an element | get() | Use the indexing operator to get an element: list[index] . |
Take a sublist | subList() | |
Replace an element or elements | set() , replaceAll() | Use the indexing operator instead of set() : list[index] = value . |
略有不同的操作
对任意集合类型的操作
描述 | Java | Kotlin |
---|---|---|
Get a collection’s size | size() | count() , size |
Get flat access to nested collection elements | collectionOfCollections.forEach(flatCollection::addAll) or collectionOfCollections.stream().flatMap().collect() | flatten() or flatMap() |
Apply the given function to every element | stream().map().collect() | map() |
Apply the provided operation to collection elements sequentially and return the accumulated result | stream().reduce() | reduce(), fold() |
Group elements by a classifier and count them | stream().collect(Collectors.groupingBy(classifier, counting())) | eachCount() |
Filter by a condition | stream().filter().collect() | filter() |
Check whether collection elements satisfy a condition | stream().noneMatch() , stream().anyMatch() , stream().allMatch() | none(), any(), all() |
Sort elements | stream().sorted().collect() | sorted() |
Take the first N elements | stream().limit(N).collect() | take(N) |
Take elements with a predicate | stream().takeWhile().collect() | takeWhile() |
Skip the first N elements | stream().skip(N).collect() | drop(N) |
Skip elements with a predicate | stream().dropWhile().collect() | dropWhile() |
Build maps from collection elements and certain values associated with them | stream().collect(toMap(keyMapper, valueMapper)) | associate() |
To perform all of the operations listed above on maps, you first need to get an entrySet
of a map.
对 list 的操作
描述 | Java | Kotlin |
---|---|---|
Sort a list into natural order | sort(null) | sort() |
Sort a list into descending order | sort(comparator) | sortDescending() |
Remove an element from a list | remove(index) , remove(element) | removeAt(index) , remove(element) or collection -= element |
Fill all elements of a list with a certain value | Collections.fill() | fill() |
Get unique elements from a list | stream().distinct().toList() | distinct() |
Java 标准库中不存在的操作
- zip(), unzip() – transform a collection.
- aggregate() – group by a condition.
- takeLast(), takeLastWhile(), dropLast(), dropLastWhile() – take or drop elements by a predicate.
- slice(), chunked(), windowed() – retrieve collection parts.
- Plus (+) and minus (-) operators – add or remove elements.
If you want to take a deep dive into zip()
, chunked()
, windowed()
, and some other operations, watch this video by Sebastian Aigner about advanced collection operations in Kotlin:
YouTube 视频:Advanced Collection Operations
可变性
In Java, there are mutable collections:
// Java
// This list is mutable!
public List<Customer> getCustomers() { ... }
Partially mutable ones:
// Java
List<String> numbers = Arrays.asList("one", "two", "three", "four");
numbers.add("five"); // Fails in runtime with `UnsupportedOperationException`
And immutable ones:
// Java
List<String> numbers = new LinkedList<>();
// This list is immutable!
List<String> immutableCollection = Collections.unmodifiableList(numbers);
immutableCollection.add("five"); // Fails in runtime with `UnsupportedOperationException`
If you write the last two pieces of code in IntelliJ IDEA, the IDE will warn you that you’re trying to modify an immutable object. This code will compile and fail in runtime with UnsupportedOperationException
. You can’t tell whether a collection is mutable by looking at its type.
Unlike in Java, in Kotlin you explicitly declare mutable or read-only collections depending on your needs. If you try to modify a read-only collection, the code won’t compile:
// Kotlin
val numbers = mutableListOf("one", "two", "three", "four")
numbers.add("five") // This is OK
val immutableNumbers = listOf("one", "two")
//immutableNumbers.add("five") // Compilation error - Unresolved reference: add
Read more about immutability on the Kotlin coding conventions page.
协变性
In Java, you can’t pass a collection with a descendant type to a function that takes a collection of the ancestor type. For example, if Rectangle
extends Shape
, you can’t pass a collection of Rectangle
elements to a function that takes a collection of Shape
elements. To make the code compilable, use the ? extends Shape
type so the function can take collections with any inheritors of Shape
:
// Java
class Shape {}
class Rectangle extends Shape {}
public void doSthWithShapes(List<? extends Shape> shapes) {
/* If using just List<Shape>, the code won't compile when calling
this function with the List<Rectangle> as the argument as below */
}
public void main() {
var rectangles = List.of(new Rectangle(), new Rectangle());
doSthWithShapes(rectangles);
}
In Kotlin, read-only collection types are covariant. This means that if a Rectangle
class inherits from the Shape
class, you can use the type List<Rectangle>
anywhere the List<Shape>
type is required. In other words, the collection types have the same subtyping relationship as the element types. Maps are covariant on the value type, but not on the key type. Mutable collections aren’t covariant – this would lead to runtime failures.
// Kotlin
open class Shape(val name: String)
class Rectangle(private val rectangleName: String) : Shape(rectangleName)
fun doSthWithShapes(shapes: List<Shape>) {
println("The shapes are: ${shapes.joinToString { it.name }}")
}
fun main() {
val rectangles = listOf(Rectangle("rhombus"), Rectangle("parallelepiped"))
doSthWithShapes(rectangles)
}
Read more about collection types here.
区间与数列
In Kotlin, you can create intervals using ranges. For example, Version(1, 11)..Version(1, 30)
includes all of the versions from 1.11
to 1.30
. You can check that your version is in the range by using the in
operator: Version(0, 9) in versionRange
.
In Java, you need to manually check whether a Version
fits both bounds:
// Java
class Version implements Comparable<Version> {
int major;
int minor;
Version(int major, int minor) {
this.major = major;
this.minor = minor;
}
@Override
public int compareTo(Version o) {
if (this.major != o.major) {
return this.major - o.major;
}
return this.minor - o.minor;
}
}
public void compareVersions() {
var minVersion = new Version(1, 11);
var maxVersion = new Version(1, 31);
System.out.println(
versionIsInRange(new Version(0, 9), minVersion, maxVersion));
System.out.println(
versionIsInRange(new Version(1, 20), minVersion, maxVersion));
}
public Boolean versionIsInRange(Version versionToCheck, Version minVersion,
Version maxVersion) {
return versionToCheck.compareTo(minVersion) >= 0
&& versionToCheck.compareTo(maxVersion) <= 0;
}
In Kotlin, you operate with a range as a whole object. You don’t need to create two variables and compare a Version
with them:
// Kotlin
class Version(val major: Int, val minor: Int): Comparable<Version> {
override fun compareTo(other: Version): Int {
if (this.major != other.major) {
return this.major - other.major
}
return this.minor - other.minor
}
}
fun main() {
val versionRange = Version(1, 11)..Version(1, 30)
println(Version(0, 9) in versionRange)
println(Version(1, 20) in versionRange)
}
As soon as you need to exclude one of the bounds, like to check whether a version is greater than or equal to (>=
) the minimum version and less than (<
) the maximum version, these inclusive ranges won’t help.
按照多个维度比较
In Java, to compare objects by several criteria, you may use the comparing() and thenComparingX() functions from the Comparator interface. For example, to compare people by their name and age:
class Person implements Comparable<Person> {
String name;
int age;
public String getName() {
return name;
}
public int getAge() {
return age;
}
Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return this.name + " " + age;
}
}
public void comparePersons() {
var persons = List.of(new Person("Jack", 35), new Person("David", 30),
new Person("Jack", 25));
System.out.println(persons.stream().sorted(Comparator
.comparing(Person::getName)
.thenComparingInt(Person::getAge)).collect(toList()));
}
In Kotlin, you just enumerate which fields you want to compare:
data class Person(
val name: String,
val age: Int
)
fun main() {
val persons = listOf(Person("Jack", 35), Person("David", 30),
Person("Jack", 25))
println(persons.sortedWith(compareBy(Person::name, Person::age)))
}
序列
In Java, you can generate a sequence of numbers this way:
// Java
int sum = IntStream.iterate(1, e -> e + 3)
.limit(10).sum();
System.out.println(sum); // Prints 145
In Kotlin, use sequences. Multi-step processing of sequences is executed lazily when possible – actual computing happens only when the result of the whole processing chain is requested.
fun main() {
//sampleStart
// Kotlin
val sum = generateSequence(1) {
it + 3
}.take(10).sum()
println(sum) // Prints 145
//sampleEnd
}
Sequences may reduce the number of steps that are needed to perform some filtering operations. See the sequence processing example, which shows the difference between Iterable
and Sequence
.
从列表中删除元素
In Java, the remove()) function accepts an index of an element to remove.
When removing an integer element, use the Integer.valueOf()
function as the argument for the remove()
function:
// Java
public void remove() {
var numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(1);
numbers.remove(1); // This removes by index
System.out.println(numbers); // [1, 3, 1]
numbers.remove(Integer.valueOf(1));
System.out.println(numbers); // [3, 1]
}
In Kotlin, there are two types of element removal: by index with removeAt() and by value with remove().
fun main() {
//sampleStart
// Kotlin
val numbers = mutableListOf(1, 2, 3, 1)
numbers.removeAt(0)
println(numbers) // [2, 3, 1]
numbers.remove(1)
println(numbers) // [2, 3]
//sampleEnd
}
遍历 map
In Java, you can traverse a map via forEach):
// Java
numbers.forEach((k,v) -> System.out.println("Key = " + k + ", Value = " + v));
In Kotlin, use a for
loop or a forEach
, similar to Java’s forEach
, to traverse a map:
// Kotlin
for ((k, v) in numbers) {
println("Key = $k, Value = $v")
}
// Or
numbers.forEach { (k, v) -> println("Key = $k, Value = $v") }
获取可能会空的集合的首末元素
In Java, you can safely get the first and the last items by checking the size of the collection and using indices:
// Java
var list = new ArrayList<>();
//...
if (list.size() > 0) {
System.out.println(list.get(0));
System.out.println(list.get(list.size() - 1));
}
You can also use the getFirst()) and getLast()) functions for Deque and its inheritors:
// Java
var deque = new ArrayDeque<>();
//...
if (deque.size() > 0) {
System.out.println(deque.getFirst());
System.out.println(deque.getLast());
}
In Kotlin, there are the special functions firstOrNull() and lastOrNull(). Using the Elvis operator, you can perform further actions right away depending on the result of a function. For example, firstOrNull()
:
// Kotlin
val emails = listOf<String>() // Might be empty
val theOldestEmail = emails.firstOrNull() ?: ""
val theFreshestEmail = emails.lastOrNull() ?: ""
由 list 创建 set
In Java, to create a Set from a List, you can use the Set.copyOf) function:
// Java
public void listToSet() {
var sourceList = List.of(1, 2, 3, 1);
var copySet = Set.copyOf(sourceList);
System.out.println(copySet);
}
In Kotlin, use the function toSet()
:
fun main() {
//sampleStart
// Kotlin
val sourceList = listOf(1, 2, 3, 1)
val copySet = sourceList.toSet()
println(copySet)
//sampleEnd
}
元素分组
In Java, you can group elements with the Collectors function groupingBy()
:
// Java
public void analyzeLogs() {
var requests = List.of(
new Request("https://kotlinlang.org/docs/home.html", 200),
new Request("https://kotlinlang.org/docs/home.html", 400),
new Request("https://kotlinlang.org/docs/comparison-to-java.html", 200)
);
var urlsAndRequests = requests.stream().collect(
Collectors.groupingBy(Request::getUrl));
System.out.println(urlsAndRequests);
}
In Kotlin, use the function groupBy():
class Request(
val url: String,
val responseCode: Int
)
fun main() {
//sampleStart
// Kotlin
val requests = listOf(
Request("https://kotlinlang.org/docs/home.html", 200),
Request("https://kotlinlang.org/docs/home.html", 400),
Request("https://kotlinlang.org/docs/comparison-to-java.html", 200)
)
println(requests.groupBy(Request::url))
//sampleEnd
}
过滤元素
In Java, to filter elements from a collection, you need to use the Stream API. The Stream API has intermediate
and terminal
operations. filter()
is an intermediate operation, which returns a stream. To receive a collection as the output, you need to use a terminal operation, like collect()
. For example, to leave only those pairs whose keys end with 1
and whose values are greater than 10
:
// Java
public void filterEndsWith() {
var numbers = Map.of("key1", 1, "key2", 2, "key3", 3, "key11", 11);
var filteredNumbers = numbers.entrySet().stream()
.filter(entry -> entry.getKey().endsWith("1") && entry.getValue() > 10)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
System.out.println(filteredNumbers);
}
In Kotlin, filtering is built into collections, and filter()
returns the same collection type that was filtered. So, all you need to write is the filter()
and its predicate:
fun main() {
//sampleStart
// Kotlin
val numbers = mapOf("key1" to 1, "key2" to 2, "key3" to 3, "key11" to 11)
val filteredNumbers = numbers.filter { (key, value) -> key.endsWith("1") && value > 10 }
println(filteredNumbers)
//sampleEnd
}
Learn more about filtering maps here.
按类型过滤元素
In Java, to filter elements by type and perform actions on them, you need to check their types with the instanceof operator and then do the type cast:
// Java
public void objectIsInstance() {
var numbers = new ArrayList<>();
numbers.add(null);
numbers.add(1);
numbers.add("two");
numbers.add(3.0);
numbers.add("four");
System.out.println("All String elements in upper case:");
numbers.stream().filter(it -> it instanceof String)
.forEach( it -> System.out.println(((String) it).toUpperCase()));
}
In Kotlin, you just call filterIsInstance
// Kotlin
fun main() {
//sampleStart
// Kotlin
val numbers = listOf(null, 1, "two", 3.0, "four")
println("All String elements in upper case:")
numbers.filterIsInstance<String>().forEach {
println(it.uppercase())
}
//sampleEnd
}
检验谓词
Some tasks require you to check whether all, none, or any elements satisfy a condition. In Java, you can do all of these checks via the Stream API functions allMatch()), noneMatch()), and anyMatch()):
// Java
public void testPredicates() {
var numbers = List.of("one", "two", "three", "four");
System.out.println(numbers.stream().noneMatch(it -> it.endsWith("e"))); // false
System.out.println(numbers.stream().anyMatch(it -> it.endsWith("e"))); // true
System.out.println(numbers.stream().allMatch(it -> it.endsWith("e"))); // false
}
In Kotlin, the extension functions none()
, any()
, and all()
are available for every Iterable object:
fun main() {
//sampleStart
// Kotlin
val numbers = listOf("one", "two", "three", "four")
println(numbers.none { it.endsWith("e") })
println(numbers.any { it.endsWith("e") })
println(numbers.all { it.endsWith("e") })
//sampleEnd
}
Learn more about test predicates.
集合转换操作
元素合拢
In Java, you can make pairs from elements with the same positions in two collections by iterating simultaneously over them:
// Java
public void zip() {
var colors = List.of("red", "brown");
var animals = List.of("fox", "bear", "wolf");
for (int i = 0; i < Math.min(colors.size(), animals.size()); i++) {
String animal = animals.get(i);
System.out.println("The " + animal.substring(0, 1).toUpperCase()
+ animal.substring(1) + " is " + colors.get(i));
}
}
If you want to do something more complex than just printing pairs of elements into the output, you can use Records. In the example above, the record would be record AnimalDescription(String animal, String color) {}
.
In Kotlin, use the zip() function to do the same thing:
fun main() {
//sampleStart
// Kotlin
val colors = listOf("red", "brown")
val animals = listOf("fox", "bear", "wolf")
println(colors.zip(animals) { color, animal ->
"The ${animal.replaceFirstChar { it.uppercase() }} is $color" })
//sampleEnd
}
zip()
returns the List of Pair objects.
If collections have different sizes, the result of
zip()
is the smaller size. The last elements of the larger collection are not included in the result.
元素关联
In Java, you can use the Stream API to associate elements with characteristics:
// Java
public void associate() {
var numbers = List.of("one", "two", "three", "four");
var wordAndLength = numbers.stream()
.collect(toMap(number -> number, String::length));
System.out.println(wordAndLength);
}
In Kotlin, use the associate() function:
fun main() {
//sampleStart
// Kotlin
val numbers = listOf("one", "two", "three", "four")
println(numbers.associateWith { it.length })
//sampleEnd
}
下一步做什么?
- Visit Kotlin Koans – complete exercises to learn Kotlin syntax. Each exercise is created as a failing unit test and your job is to make it pass.
- Look through other Kotlin idioms.
- Learn how to convert existing Java code to Kotlin with the Java to Kotlin converter.
- Discover collections in Kotlin.
If you have a favorite idiom, we invite you to share it by sending a pull request.