标准Kotlin库中提供了哪些Java 8 Stream.collect等价物?

时间:2016-01-06 20:34:35

标签: java kotlin collections java-8 java-stream

在Java 8中,recommended to not be loaded允许对集合进行聚合。在Kotlin中,除了作为stdlib中的扩展函数的集合之外,它不以相同的方式存在。但目前尚不清楚不同用例的等价性。

例如,Stream.collect是为Java 8编写的示例,当将它们移植到Kolin时,在使用不同的JDK版本时不能使用Java 8类,因此它们应该以不同的方式编写。

在网上显示Kotlin集合示例的资源方面,它们通常是微不足道的,并没有真正与相同的用例进行比较。什么是真正匹配案例的好例子,例如为Java 8 {{1}}记录的案例?列表是:

  • 将名称累积到列表中
  • 将名称累积到TreeSet中
  • 将元素转换为字符串并将它们连接起来,以逗号分隔
  • 计算员工工资总额
  • 按部门分组员工
  • 按部门计算工资总额
  • 将学生分成传球和失败

上面链接的JavaDoc中的详细信息。

注意: 这个问题是由作者(top of the JavaDoc for Collectors)故意编写和回答的,因此对于常见问题的Kotlin主题的惯用解答存在于SO中。还要澄清为Kotlin的alphas写的一些非常古老的答案,这些答案对于当前的Kotlin来说是不准确的。

4 个答案:

答案 0 :(得分:225)

Kotlin stdlib中有函数用于平均,计数,清晰,过滤,查找,分组,连接,映射,最小化,最大化,分区,切片,排序,求和,到/从数组到/从列表到/来自地图,联合,共同迭代,所有功能范例等等。因此,您可以使用它们创建小的1行,并且不需要使用更复杂的Java 8语法。

我认为内置的Java 8 Collectors类中唯一缺少的是摘要(但在another answer to this question中是一个简单的解决方案)

两者中缺少的一件事就是按计数进行批处理,这可以在another Stack Overflow answer中看到并且也有一个简单的答案。另一个有趣的案例是Stack Overflow:Idiomatic way to spilt sequence into three lists using Kotlin。如果您想为其他目的创建Stream.collect之类的内容,请参阅Custom Stream.collect in Kotlin

编辑11.08.2017:在kotlin 1.2 M2中添加了分块/窗口收集操作,请参阅https://blog.jetbrains.com/kotlin/2017/08/kotlin-1-2-m2-is-out/

在创建可能已经存在的新功能之前,总是很好地探索API Reference for kotlin.collections

以下是从Java 8 Stream.collect示例到Kotlin中的等效内容的一些转换:

将名称累积到列表中

// Java:  
List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());
// Kotlin:
val list = people.map { it.name }  // toList() not needed

将元素转换为字符串并将它们连接起来,用逗号分隔

// Java:
String joined = things.stream()
                       .map(Object::toString)
                       .collect(Collectors.joining(", "));
// Kotlin:
val joined = things.joinToString(", ")

计算员工工资总额

// Java:
int total = employees.stream()
                      .collect(Collectors.summingInt(Employee::getSalary)));
// Kotlin:
val total = employees.sumBy { it.salary }

按部门分组员工

// Java:
Map<Department, List<Employee>> byDept
     = employees.stream()
                .collect(Collectors.groupingBy(Employee::getDepartment));
// Kotlin:
val byDept = employees.groupBy { it.department }

按部门计算工资总额

// Java:
Map<Department, Integer> totalByDept
     = employees.stream()
                .collect(Collectors.groupingBy(Employee::getDepartment,
                     Collectors.summingInt(Employee::getSalary)));
// Kotlin:
val totalByDept = employees.groupBy { it.dept }.mapValues { it.value.sumBy { it.salary }}

将学生分成传球和失败

// Java:
Map<Boolean, List<Student>> passingFailing =
     students.stream()
             .collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));
// Kotlin:
val passingFailing = students.partition { it.grade >= PASS_THRESHOLD }

男性会员姓名

// Java:
List<String> namesOfMaleMembers = roster
    .stream()
    .filter(p -> p.getGender() == Person.Sex.MALE)
    .map(p -> p.getName())
    .collect(Collectors.toList());
// Kotlin:
val namesOfMaleMembers = roster.filter { it.gender == Person.Sex.MALE }.map { it.name }

按性别划分的名册成员的名称

// Java:
Map<Person.Sex, List<String>> namesByGender =
      roster.stream().collect(
        Collectors.groupingBy(
            Person::getGender,                      
            Collectors.mapping(
                Person::getName,
                Collectors.toList())));
// Kotlin:
val namesByGender = roster.groupBy { it.gender }.mapValues { it.value.map { it.name } }   

将列表过滤到其他列表

// Java:
List<String> filtered = items.stream()
    .filter( item -> item.startsWith("o") )
    .collect(Collectors.toList());
// Kotlin:
val filtered = items.filter { it.startsWith('o') } 

在列表中查找最短字符串

// Java:
String shortest = items.stream()
    .min(Comparator.comparing(item -> item.length()))
    .get();
// Kotlin:
val shortest = items.minBy { it.length }

在应用过滤器后计算列表中的项目

// Java:
long count = items.stream().filter( item -> item.startsWith("t")).count();
// Kotlin:
val count = items.filter { it.startsWith('t') }.size
// but better to not filter, but count with a predicate
val count = items.count { it.startsWith('t') }

并且就此而言......在所有情况下,模拟Stream.collect都不需要特殊的折叠,缩小或其他功能。如果您还有其他用例,请在评论中添加它们,我们可以看到!

关于懒惰

如果您想延迟处理链,可以在链之前使用Sequence转换为asSequence()。在函数链的末尾,您通常最终得到Sequence。然后,您可以使用toList()toSet()toMap()或其他一些功能来最终实现Sequence

// switch to and from lazy
val someList = items.asSequence().filter { ... }.take(10).map { ... }.toList()

// switch to lazy, but sorted() brings us out again at the end
val someList = items.asSequence().filter { ... }.take(10).map { ... }.sorted()

为什么没有类型?!?

您会注意到Kotlin示例未指定类型。这是因为Kotlin具有完整的类型推断并且在编译时完全是类型安全的。比Java更多,因为它也有可空类型,可以帮助防止可怕的NPE。所以这在Kotlin:

val someList = people.filter { it.age <= 30 }.map { it.name }

与:

相同
val someList: List<String> = people.filter { it.age <= 30 }.map { it.name }

因为Kotlin知道people是什么,people.ageInt因此,过滤器表达式只允许与Int进行比较,而people.nameString因此map步骤会生成List<String>List String的唯一people

现在,如果null可能是List<People>?,那么在val someList = people?.filter { it.age <= 30 }?.map { it.name } 中就是:

List<String>?

返回需要进行空检查的readfile()或使用其他Kotlin运算符之一获取可空值,请参阅此Kotlin idiomatic way to deal with nullable values以及Idiomatic way of handling nullable or empty list in Kotlin

另见:

答案 1 :(得分:43)

对于其他示例,以下是Java 8 Stream Tutorial转换为Kotlin的所有样本。每个示例的标题都源自源文章:

流如何工作

// Java:
List<String> myList = Arrays.asList("a1", "a2", "b1", "c2", "c1");

myList.stream()
      .filter(s -> s.startsWith("c"))
      .map(String::toUpperCase)
     .sorted()
     .forEach(System.out::println);

// C1
// C2
// Kotlin:
val list = listOf("a1", "a2", "b1", "c2", "c1")
list.filter { it.startsWith('c') }.map (String::toUpperCase).sorted()
        .forEach (::println)

不同种类的流#1

// Java:
Arrays.asList("a1", "a2", "a3")
    .stream()
    .findFirst()
    .ifPresent(System.out::println);    
// Kotlin:
listOf("a1", "a2", "a3").firstOrNull()?.apply(::println)

或者,在String上创建一个名为ifPresent的扩展函数:

// Kotlin:
inline fun String?.ifPresent(thenDo: (String)->Unit) = this?.apply { thenDo(this) }

// now use the new extension function:
listOf("a1", "a2", "a3").firstOrNull().ifPresent(::println)

另请参阅:apply() function

另请参阅:Extension Functions

另请参阅:?. Safe Call operator,以及一般的可空性:In Kotlin, what is the idiomatic way to deal with nullable values, referencing or converting them

不同种类的流#2

// Java:
Stream.of("a1", "a2", "a3")
    .findFirst()
    .ifPresent(System.out::println);    
// Kotlin:
sequenceOf("a1", "a2", "a3").firstOrNull()?.apply(::println)

不同种类的流#3

// Java:
IntStream.range(1, 4).forEach(System.out::println);
// Kotlin:  (inclusive range)
(1..3).forEach(::println)

不同种类的流#4

// Java:
Arrays.stream(new int[] {1, 2, 3})
    .map(n -> 2 * n + 1)
    .average()
    .ifPresent(System.out::println); // 5.0    
// Kotlin:
arrayOf(1,2,3).map { 2 * it + 1}.average().apply(::println)

不同种类的流#5

// Java:
Stream.of("a1", "a2", "a3")
    .map(s -> s.substring(1))
    .mapToInt(Integer::parseInt)
    .max()
    .ifPresent(System.out::println);  // 3
// Kotlin:
sequenceOf("a1", "a2", "a3")
    .map { it.substring(1) }
    .map(String::toInt)
    .max().apply(::println)

不同种类的流#6

// Java:
IntStream.range(1, 4)
    .mapToObj(i -> "a" + i)
    .forEach(System.out::println);

// a1
// a2
// a3    
// Kotlin:  (inclusive range)
(1..3).map { "a$it" }.forEach(::println)

不同种类的流#7

// Java:
Stream.of(1.0, 2.0, 3.0)
    .mapToInt(Double::intValue)
    .mapToObj(i -> "a" + i)
    .forEach(System.out::println);

// a1
// a2
// a3
// Kotlin:
sequenceOf(1.0, 2.0, 3.0).map(Double::toInt).map { "a$it" }.forEach(::println)

为什么订单很重要

Java 8 Stream Tutorial的这一部分与Kotlin和Java相同。

重用Streams

在Kotlin中,它取决于收集的类型是否可以多次食用。 Sequence每次都会生成一个新的迭代器,除非它断言“只使用一次”,否则每次执行时它都会重置为开始。因此,虽然以下在Java 8流中失败,但在Kotlin中工作:

// Java:
Stream<String> stream =
Stream.of("d2", "a2", "b1", "b3", "c").filter(s -> s.startsWith("b"));

stream.anyMatch(s -> true);    // ok
stream.noneMatch(s -> true);   // exception
// Kotlin:  
val stream = listOf("d2", "a2", "b1", "b3", "c").asSequence().filter { it.startsWith('b' ) }

stream.forEach(::println) // b1, b2

println("Any B ${stream.any { it.startsWith('b') }}") // Any B true
println("Any C ${stream.any { it.startsWith('c') }}") // Any C false

stream.forEach(::println) // b1, b2

在Java中获得相同的行为:

// Java:
Supplier<Stream<String>> streamSupplier =
    () -> Stream.of("d2", "a2", "b1", "b3", "c")
          .filter(s -> s.startsWith("a"));

streamSupplier.get().anyMatch(s -> true);   // ok
streamSupplier.get().noneMatch(s -> true);  // ok

因此,在Kotlin中,数据提供者决定它是否可以重置并提供新的迭代器。但是,如果您想故意将Sequence限制为一次迭代,则可以使用constrainOnce() Sequence函数,如下所示:

val stream = listOf("d2", "a2", "b1", "b3", "c").asSequence().filter { it.startsWith('b' ) }
        .constrainOnce()

stream.forEach(::println) // b1, b2
stream.forEach(::println) // Error:java.lang.IllegalStateException: This sequence can be consumed only once. 

高级操作

收集示例#5 (是的,我跳过已经在其他答案中的那些)

// Java:
String phrase = persons
        .stream()
        .filter(p -> p.age >= 18)
        .map(p -> p.name)
        .collect(Collectors.joining(" and ", "In Germany ", " are of legal age."));

    System.out.println(phrase);
    // In Germany Max and Peter and Pamela are of legal age.    
// Kotlin:
val phrase = persons.filter { it.age >= 18 }.map { it.name }
        .joinToString(" and ", "In Germany ", " are of legal age.")

println(phrase)
// In Germany Max and Peter and Pamela are of legal age.

作为旁注,在Kotlin中,我们可以创建简单的data classes并实例化测试数据,如下所示:

// Kotlin:
// data class has equals, hashcode, toString, and copy methods automagically
data class Person(val name: String, val age: Int) 

val persons = listOf(Person("Tod", 5), Person("Max", 33), 
                     Person("Frank", 13), Person("Peter", 80),
                     Person("Pamela", 18))

收集示例#6

// Java:
Map<Integer, String> map = persons
        .stream()
        .collect(Collectors.toMap(
                p -> p.age,
                p -> p.name,
                (name1, name2) -> name1 + ";" + name2));

System.out.println(map);
// {18=Max, 23=Peter;Pamela, 12=David}    

好的,这是Kotlin的一个更有意义的案例。首先是探索从集合/序列中创建Map的变体的错误答案:

// Kotlin:
val map1 = persons.map { it.age to it.name }.toMap()
println(map1)
// output: {18=Max, 23=Pamela, 12=David} 
// Result: duplicates overridden, no exception similar to Java 8

val map2 = persons.toMap({ it.age }, { it.name })
println(map2)
// output: {18=Max, 23=Pamela, 12=David} 
// Result: same as above, more verbose, duplicates overridden

val map3 = persons.toMapBy { it.age }
println(map3)
// output: {18=Person(name=Max, age=18), 23=Person(name=Pamela, age=23), 12=Person(name=David, age=12)}
// Result: duplicates overridden again

val map4 = persons.groupBy { it.age }
println(map4)
// output: {18=[Person(name=Max, age=18)], 23=[Person(name=Peter, age=23), Person(name=Pamela, age=23)], 12=[Person(name=David, age=12)]}
// Result: closer, but now have a Map<Int, List<Person>> instead of Map<Int, String>

val map5 = persons.groupBy { it.age }.mapValues { it.value.map { it.name } }
println(map5)
// output: {18=[Max], 23=[Peter, Pamela], 12=[David]}
// Result: closer, but now have a Map<Int, List<String>> instead of Map<Int, String>

现在回答正确答案:

// Kotlin:
val map6 = persons.groupBy { it.age }.mapValues { it.value.joinToString(";") { it.name } }

println(map6)
// output: {18=Max, 23=Peter;Pamela, 12=David}
// Result: YAY!!

我们只需加入匹配值即可折叠列表,并提供转换为jointToString以从Person实例移至Person.name

收集示例#7

好的,这个可以很容易地在没有自定义Collector的情况下完成,所以让我们以Kotlin的方式解决它,然后设计一个新的例子来展示如何对Collector.summarizingInt进行类似的处理本土存在于科特林。

// Java:
Collector<Person, StringJoiner, String> personNameCollector =
Collector.of(
        () -> new StringJoiner(" | "),          // supplier
        (j, p) -> j.add(p.name.toUpperCase()),  // accumulator
        (j1, j2) -> j1.merge(j2),               // combiner
        StringJoiner::toString);                // finisher

String names = persons
        .stream()
        .collect(personNameCollector);

System.out.println(names);  // MAX | PETER | PAMELA | DAVID    
// Kotlin:
val names = persons.map { it.name.toUpperCase() }.joinToString(" | ")

这不是我的错,他们选择了一个简单的例子!!! 好的,这是Kotlin的一个新的summarizingInt方法和一个匹配的样本:

SummarizingInt示例

// Java:
IntSummaryStatistics ageSummary =
    persons.stream()
           .collect(Collectors.summarizingInt(p -> p.age));

System.out.println(ageSummary);
// IntSummaryStatistics{count=4, sum=76, min=12, average=19.000000, max=23}    
// Kotlin:

// something to hold the stats...
data class SummaryStatisticsInt(var count: Int = 0,  
                                var sum: Int = 0, 
                                var min: Int = Int.MAX_VALUE, 
                                var max: Int = Int.MIN_VALUE, 
                                var avg: Double = 0.0) {
    fun accumulate(newInt: Int): SummaryStatisticsInt {
        count++
        sum += newInt
        min = min.coerceAtMost(newInt)
        max = max.coerceAtLeast(newInt)
        avg = sum.toDouble() / count
        return this
    }
}

// Now manually doing a fold, since Stream.collect is really just a fold
val stats = persons.fold(SummaryStatisticsInt()) { stats, person -> stats.accumulate(person.age) }

println(stats)
// output: SummaryStatisticsInt(count=4, sum=76, min=12, max=23, avg=19.0)

但是最好创建一个扩展函数,2实际上匹配Kotlin stdlib中的样式:

// Kotlin:
inline fun Collection<Int>.summarizingInt(): SummaryStatisticsInt
        = this.fold(SummaryStatisticsInt()) { stats, num -> stats.accumulate(num) }

inline fun <T: Any> Collection<T>.summarizingInt(transform: (T)->Int): SummaryStatisticsInt =
        this.fold(SummaryStatisticsInt()) { stats, item -> stats.accumulate(transform(item)) }

现在您有两种方法可以使用新的summarizingInt函数:

val stats2 = persons.map { it.age }.summarizingInt()

// or

val stats3 = persons.summarizingInt { it.age }

所有这些产生相同的结果。我们还可以创建此扩展以处理Sequence和适当的原始类型。

为了好玩,compare the Java JDK code vs. Kotlin custom code需要实现此摘要。

答案 2 :(得分:3)

在某些情况下,很难避免调用collect(Collectors.toList())或类似内容。在这些情况下,您可以使用扩展功能更快速地更改为Kotlin等效项,例如:

fun <T: Any> Stream<T>.toList(): List<T> = this.collect(Collectors.toList<T>())
fun <T: Any> Stream<T>.asSequence(): Sequence<T> = this.iterator().asSequence()

然后,您只需stream.toList()stream.asSequence()即可返回Kotlin API。 Files.list(path)这样的案例会在您不希望的情况下强迫您进入Stream,这些扩展可以帮助您转回标准集合和Kotlin API。

答案 3 :(得分:2)

更多关于懒惰

让我们以Jayson给出的“按部门计算工资计算总额”的示例解决方案:

val totalByDept = employees.groupBy { it.dept }.mapValues { it.value.sumBy { it.salary }}

为了使这个懒惰(即避免在groupBy步骤中创建中间地图),不可能使用asSequence()。相反,我们必须使用groupingByfold操作:

val totalByDept = employees.groupingBy { it.dept }.fold(0) { acc, e -> acc + e.salary }

对于某些人来说,这甚至可能更具可读性,因为您没有处理地图条目:解决方案中的it.value部分一开始也让我感到困惑。

由于这是一种常见情况,我们不希望每次都写出fold,因此最好只在sumBy上提供通用的Grouping函数:< / p>

public inline fun <T, K> Grouping<T, K>.sumBy(
        selector: (T) -> Int
): Map<K, Int> = 
        fold(0) { acc, element -> acc + selector(element) }

这样我们就可以简单地写一下:

val totalByDept = employees.groupingBy { it.dept }.sumBy { it.salary }
相关问题