Created
July 27, 2020 08:28
-
-
Save houssemzaier/f1c68e1679e00419221a0f0e3f9444b2 to your computer and use it in GitHub Desktop.
azaz
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package fr.francetv.francetvsport.arch.presentation.main.navigations | |
import java.io.IOException | |
import java.util.* | |
import java.util.stream.Collectors | |
object GroupByDemoInJava8 { | |
@Throws(IOException::class) | |
@JvmStatic | |
fun main(args: Array<String>) { | |
val people: MutableList<Person> = ArrayList() | |
people.add(Person("John", "London", 21)) | |
people.add(Person("Swann", "London", 21)) | |
people.add(Person("Kevin", "London", 23)) | |
people.add(Person("Monobo", "Tokyo", 23)) | |
people.add(Person("Sam", "Paris", 23)) | |
people.add(Person("Nadal", "Paris", 31)) | |
// Now let's group all person by city in pre Java 8 world | |
val personsByCity: MutableMap<String, MutableList<Person>?> = HashMap() | |
for (p in people) { | |
if (!personsByCity.containsKey(p.city)) { | |
personsByCity[p.city] = ArrayList() | |
} | |
personsByCity[p.city]!!.add(p) | |
} | |
println("Persons grouped by cities : $personsByCity") | |
// // Java 8 way to group object by a property key | |
val personsByCity2 = people.stream().collect(Collectors.groupingBy { p: Person -> p.city }) | |
val personByAge = people.stream().collect(Collectors.groupingBy { p: Person -> p.age }) | |
// System.out.println("Person grouped by age in Java 8: " + personByAge); | |
people.groupBy { it.city }.also { println("KT with groupBy $it") } | |
people.groupingBy { it.city }.sourceIterator().forEach { | |
println("KT with groupingBy $it") | |
} | |
people.groupingBy { it.city }.fold(mutableMapOf<String, MutableList<Person>>()) { map, person -> | |
val persons = map[person.city] ?: mutableListOf() | |
persons.add(person) | |
map.putIfAbsent(person.city, persons) | |
map | |
}.also { | |
println("MP with effff $it") | |
} | |
} | |
} | |
private data class Person(var name: String, var city: String, var age: Int) { | |
override fun toString(): String { | |
return String.format("%s(%s,%d)", name, city, age) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment