Jmnote bot (토론 | 기여) 잔글 (봇: 자동으로 텍스트 교체 (-</source> +</syntaxhighlight>, -<source +<syntaxhighlight )) |
|||
(사용자 2명의 중간 판 4개는 보이지 않습니다) | |||
18번째 줄: | 18번째 줄: | ||
==Introduction== | ==Introduction== | ||
{{참고|#TestShop.kt & Shop.kt}} | {{참고|#TestShop.kt & Shop.kt}} | ||
< | <syntaxhighlight lang='kotlin'> | ||
</ | fun Shop.getSetOfCustomers(): Set<Customer> = customers.toSet() | ||
</syntaxhighlight> | |||
==Filter map== | ==Filter map== | ||
{{참고|#TestShop.kt & Shop.kt}} | {{참고|#TestShop.kt & Shop.kt}} | ||
< | <syntaxhighlight lang='kotlin'> | ||
</ | // Return the set of cities the customers are from | ||
fun Shop.getCitiesCustomersAreFrom(): Set<City> = customers.map { it.city }.toSet() | |||
// Return a list of the customers who live in the given city | |||
fun Shop.getCustomersFrom(city: City): List<Customer> = customers.filter { it.city == city } | |||
</syntaxhighlight> | |||
==All Any and other predicates== | ==All Any and other predicates== | ||
{{참고|#TestShop.kt & Shop.kt}} | {{참고|#TestShop.kt & Shop.kt}} | ||
< | <syntaxhighlight lang='kotlin'> | ||
</ | // Return true if all customers are from the given city | ||
fun Shop.checkAllCustomersAreFrom(city: City): Boolean = customers.all { it.city == city } | |||
// Return true if there is at least one customer from the given city | |||
fun Shop.hasCustomerFrom(city: City): Boolean = customers.any { it.city == city } | |||
// Return the number of customers from the given city | |||
fun Shop.countCustomersFrom(city: City): Int = customers.count { it.city == city } | |||
// Return a customer who lives in the given city, or null if there is none | |||
fun Shop.findAnyCustomerFrom(city: City): Customer? = customers.find { it.city == city } | |||
</syntaxhighlight> | |||
==FlatMap== | ==FlatMap== | ||
{{참고|#TestShop.kt & Shop.kt}} | {{참고|#TestShop.kt & Shop.kt}} | ||
< | <syntaxhighlight lang='kotlin'> | ||
</ | // Return all products this customer has ordered | ||
val Customer.orderedProducts: Set<Product> get() { | |||
return orders.flatMap { it.products }.toSet() | |||
} | |||
// Return all products that were ordered by at least one customer | |||
val Shop.allOrderedProducts: Set<Product> get() { | |||
return customers.flatMap { it.orderedProducts }.toSet() | |||
} | |||
</syntaxhighlight> | |||
==Max min== | ==Max min== | ||
{{참고|#TestShop.kt & Shop.kt}} | {{참고|#TestShop.kt & Shop.kt}} | ||
< | <syntaxhighlight lang='kotlin'> | ||
</ | // Return a customer whose order count is the highest among all customers | ||
fun Shop.getCustomerWithMaximumNumberOfOrders(): Customer? = customers.maxBy { it.orders.size } | |||
// Return the most expensive product which has been ordered | |||
fun Customer.getMostExpensiveOrderedProduct(): Product? = orders.flatMap { it.products }.maxBy { it.price } | |||
</syntaxhighlight> | |||
==Sort== | ==Sort== | ||
{{참고|#TestShop.kt & Shop.kt}} | {{참고|#TestShop.kt & Shop.kt}} | ||
< | <syntaxhighlight lang='kotlin'> | ||
</ | // Return a list of customers, sorted by the ascending number of orders they made | ||
fun Shop.getCustomersSortedByNumberOfOrders(): List<Customer> = customers.sortedBy { it.orders.size } | |||
</syntaxhighlight> | |||
==Sum== | ==Sum== | ||
{{참고|#TestShop.kt & Shop.kt}} | {{참고|#TestShop.kt & Shop.kt}} | ||
< | <syntaxhighlight lang='kotlin'> | ||
</ | // Return the sum of prices of all products that a customer has ordered. | ||
// Note: the customer may order the same product for several times. | |||
fun Customer.getTotalOrderPrice(): Double = orders.flatMap { it.products }.sumByDouble { it.price } | |||
</syntaxhighlight> | |||
==GroupBy== | ==GroupBy== | ||
{{참고|#TestShop.kt & Shop.kt}} | {{참고|#TestShop.kt & Shop.kt}} | ||
< | <syntaxhighlight lang='kotlin'> | ||
</ | // Return a map of the customers living in each city | ||
fun Shop.groupCustomersByCity(): Map<City, List<Customer>> = customers.groupBy { it.city } | |||
</syntaxhighlight> | |||
==Partition== | ==Partition== | ||
{{참고|#TestShop.kt & Shop.kt}} | {{참고|#TestShop.kt & Shop.kt}} | ||
< | <syntaxhighlight lang='kotlin'> | ||
// Return customers who have more undelivered orders than delivered | // Return customers who have more undelivered orders than delivered | ||
fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> = customers.filter { | fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> = customers.filter { | ||
64번째 줄: | 102번째 줄: | ||
undelivered.size > delivered.size | undelivered.size > delivered.size | ||
}.toSet() | }.toSet() | ||
</ | </syntaxhighlight> | ||
==Fold== | ==Fold== | ||
{{참고|#TestShop.kt & Shop.kt}} | {{참고|#TestShop.kt & Shop.kt}} | ||
< | <syntaxhighlight lang='kotlin'> | ||
// Return the set of products that were ordered by every customer | // Return the set of products that were ordered by every customer | ||
fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> { | fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> { | ||
77번째 줄: | 115번째 줄: | ||
}) | }) | ||
} | } | ||
</ | </syntaxhighlight> | ||
==Compound tasks== | ==Compound tasks== | ||
{{참고|#TestShop.kt & Shop.kt}} | {{참고|#TestShop.kt & Shop.kt}} | ||
< | <syntaxhighlight lang='kotlin'> | ||
// Return the most expensive product among all delivered products | // Return the most expensive product among all delivered products | ||
// (use the Order.isDelivered flag) | // (use the Order.isDelivered flag) | ||
97번째 줄: | 135번째 줄: | ||
return orders.flatMap { it.products } | return orders.flatMap { it.products } | ||
} | } | ||
</ | </syntaxhighlight> | ||
==Get used to new style== | ==Get used to new style== | ||
{{참고|#TestShop.kt & Shop.kt}} | {{참고|#TestShop.kt & Shop.kt}} | ||
< | {{소스헤더|Java}} | ||
<syntaxhighlight lang='java'> | |||
public Collection<String> doSomethingStrangeWithCollection( | |||
Collection<String> collection | |||
) { | |||
Map<Integer, List<String>> groupsByLength = Maps.newHashMap(); | |||
for (String s : collection) { | |||
List<String> strings = groupsByLength.get(s.length()); | |||
if (strings == null) { | |||
strings = Lists.newArrayList(); | |||
groupsByLength.put(s.length(), strings); | |||
} | |||
strings.add(s); | |||
} | |||
int maximumSizeOfGroup = 0; | |||
for (List<String> group : groupsByLength.values()) { | |||
if (group.size() > maximumSizeOfGroup) { | |||
maximumSizeOfGroup = group.size(); | |||
} | |||
} | |||
for (List<String> group : groupsByLength.values()) { | |||
if (group.size() == maximumSizeOfGroup) { | |||
return group; | |||
} | |||
} | |||
return null; | |||
} | |||
</syntaxhighlight> | |||
{{소스헤더|Kotlin}} | |||
<syntaxhighlight lang='kotlin'> | |||
fun doSomethingStrangeWithCollection(collection: Collection<String>): Collection<String>? { | fun doSomethingStrangeWithCollection(collection: Collection<String>): Collection<String>? { | ||
110번째 줄: | 179번째 줄: | ||
return groupsByLength.values.firstOrNull { group -> group.size == maximumSizeOfGroup } | return groupsByLength.values.firstOrNull { group -> group.size == maximumSizeOfGroup } | ||
} | } | ||
</ | </syntaxhighlight> | ||
==TestShop.kt & Shop.kt== | ==TestShop.kt & Shop.kt== | ||
{{소스헤더|TestShop.kt}} | {{소스헤더|TestShop.kt}} | ||
< | <syntaxhighlight lang='kotlin'> | ||
//products | //products | ||
val idea = Product("IntelliJ IDEA Ultimate", 199.0) | val idea = Product("IntelliJ IDEA Ultimate", 199.0) | ||
193번째 줄: | 262번째 줄: | ||
Tokyo to listOf(asuka, riku) | Tokyo to listOf(asuka, riku) | ||
).mapValues { it.value.map { name -> customers[name] } } | ).mapValues { it.value.map { name -> customers[name] } } | ||
</ | </syntaxhighlight> | ||
{{소스헤더|Shop.kt}} | {{소스헤더|Shop.kt}} | ||
< | <syntaxhighlight lang='kotlin'> | ||
data class Shop(val name: String, val customers: List<Customer>) | data class Shop(val name: String, val customers: List<Customer>) | ||
| | ||
211번째 줄: | 280번째 줄: | ||
override fun toString() = name | override fun toString() = name | ||
} | } | ||
</ | </syntaxhighlight> |
2020년 11월 2일 (월) 02:55 기준 최신판
# | Kotlin Koans |
---|---|
Kotlin Koans - Introduction | |
Kotlin Koans - Conventions | |
Kotlin Koans - Collections | |
Kotlin Koans - Properties | |
Kotlin Koans - Builders | |
Kotlin Koans - Generics |
1 Introduction[ | ]
#TestShop.kt & Shop.kt 문서를 참고하십시오.
Kotlin
Copy
fun Shop.getSetOfCustomers(): Set<Customer> = customers.toSet()
2 Filter map[ | ]
#TestShop.kt & Shop.kt 문서를 참고하십시오.
Kotlin
Copy
// Return the set of cities the customers are from
fun Shop.getCitiesCustomersAreFrom(): Set<City> = customers.map { it.city }.toSet()
// Return a list of the customers who live in the given city
fun Shop.getCustomersFrom(city: City): List<Customer> = customers.filter { it.city == city }
3 All Any and other predicates[ | ]
#TestShop.kt & Shop.kt 문서를 참고하십시오.
Kotlin
Copy
// Return true if all customers are from the given city
fun Shop.checkAllCustomersAreFrom(city: City): Boolean = customers.all { it.city == city }
// Return true if there is at least one customer from the given city
fun Shop.hasCustomerFrom(city: City): Boolean = customers.any { it.city == city }
// Return the number of customers from the given city
fun Shop.countCustomersFrom(city: City): Int = customers.count { it.city == city }
// Return a customer who lives in the given city, or null if there is none
fun Shop.findAnyCustomerFrom(city: City): Customer? = customers.find { it.city == city }
4 FlatMap[ | ]
#TestShop.kt & Shop.kt 문서를 참고하십시오.
Kotlin
Copy
// Return all products this customer has ordered
val Customer.orderedProducts: Set<Product> get() {
return orders.flatMap { it.products }.toSet()
}
// Return all products that were ordered by at least one customer
val Shop.allOrderedProducts: Set<Product> get() {
return customers.flatMap { it.orderedProducts }.toSet()
}
5 Max min[ | ]
#TestShop.kt & Shop.kt 문서를 참고하십시오.
Kotlin
Copy
// Return a customer whose order count is the highest among all customers
fun Shop.getCustomerWithMaximumNumberOfOrders(): Customer? = customers.maxBy { it.orders.size }
// Return the most expensive product which has been ordered
fun Customer.getMostExpensiveOrderedProduct(): Product? = orders.flatMap { it.products }.maxBy { it.price }
6 Sort[ | ]
#TestShop.kt & Shop.kt 문서를 참고하십시오.
Kotlin
Copy
// Return a list of customers, sorted by the ascending number of orders they made
fun Shop.getCustomersSortedByNumberOfOrders(): List<Customer> = customers.sortedBy { it.orders.size }
7 Sum[ | ]
#TestShop.kt & Shop.kt 문서를 참고하십시오.
Kotlin
Copy
// Return the sum of prices of all products that a customer has ordered.
// Note: the customer may order the same product for several times.
fun Customer.getTotalOrderPrice(): Double = orders.flatMap { it.products }.sumByDouble { it.price }
8 GroupBy[ | ]
#TestShop.kt & Shop.kt 문서를 참고하십시오.
Kotlin
Copy
// Return a map of the customers living in each city
fun Shop.groupCustomersByCity(): Map<City, List<Customer>> = customers.groupBy { it.city }
9 Partition[ | ]
#TestShop.kt & Shop.kt 문서를 참고하십시오.
Kotlin
Copy
// Return customers who have more undelivered orders than delivered
fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> = customers.filter {
val (delivered, undelivered) = it.orders.partition { it.isDelivered }
undelivered.size > delivered.size
}.toSet()
10 Fold[ | ]
#TestShop.kt & Shop.kt 문서를 참고하십시오.
Kotlin
Copy
// Return the set of products that were ordered by every customer
fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> {
val allProducts = customers.flatMap { it.orders.flatMap { it.products }}.toSet()
return customers.fold(allProducts, {
orderedByAll, customer ->
orderedByAll.intersect(customer.orders.flatMap { it.products }.toSet())
})
}
11 Compound tasks[ | ]
#TestShop.kt & Shop.kt 문서를 참고하십시오.
Kotlin
Copy
// Return the most expensive product among all delivered products
// (use the Order.isDelivered flag)
fun Customer.getMostExpensiveDeliveredProduct(): Product? {
return orders.filter { it.isDelivered }.flatMap { it.products }.maxBy { it.price }
}
// Return how many times the given product was ordered.
// Note: a customer may order the same product for several times.
fun Shop.getNumberOfTimesProductWasOrdered(product: Product): Int {
return customers.flatMap { it.getOrderedProductsList() }.count { it == product }
}
fun Customer.getOrderedProductsList(): List<Product> {
return orders.flatMap { it.products }
}
12 Get used to new style[ | ]
#TestShop.kt & Shop.kt 문서를 참고하십시오.
Java
Java
Copy
public Collection<String> doSomethingStrangeWithCollection(
Collection<String> collection
) {
Map<Integer, List<String>> groupsByLength = Maps.newHashMap();
for (String s : collection) {
List<String> strings = groupsByLength.get(s.length());
if (strings == null) {
strings = Lists.newArrayList();
groupsByLength.put(s.length(), strings);
}
strings.add(s);
}
int maximumSizeOfGroup = 0;
for (List<String> group : groupsByLength.values()) {
if (group.size() > maximumSizeOfGroup) {
maximumSizeOfGroup = group.size();
}
}
for (List<String> group : groupsByLength.values()) {
if (group.size() == maximumSizeOfGroup) {
return group;
}
}
return null;
}
Kotlin
Kotlin
Copy
fun doSomethingStrangeWithCollection(collection: Collection<String>): Collection<String>? {
val groupsByLength = collection. groupBy { s -> s.length }
val maximumSizeOfGroup = groupsByLength.values.map { group -> group.size }.max()
return groupsByLength.values.firstOrNull { group -> group.size == maximumSizeOfGroup }
}
13 TestShop.kt & Shop.kt[ | ]
TestShop.kt
Kotlin
Copy
//products
val idea = Product("IntelliJ IDEA Ultimate", 199.0)
val reSharper = Product("ReSharper", 149.0)
val dotTrace = Product("DotTrace", 159.0)
val dotMemory = Product("DotTrace", 129.0)
val dotCover = Product("DotCover", 99.0)
val appCode = Product("AppCode", 99.0)
val phpStorm = Product("PhpStorm", 99.0)
val pyCharm = Product("PyCharm", 99.0)
val rubyMine = Product("RubyMine", 99.0)
val webStorm = Product("WebStorm", 49.0)
val teamCity = Product("TeamCity", 299.0)
val youTrack = Product("YouTrack", 500.0)
//customers
val lucas = "Lucas"
val cooper = "Cooper"
val nathan = "Nathan"
val reka = "Reka"
val bajram = "Bajram"
val asuka = "Asuka"
val riku = "Riku"
//cities
val Canberra = City("Canberra")
val Vancouver = City("Vancouver")
val Budapest = City("Budapest")
val Ankara = City("Ankara")
val Tokyo = City("Tokyo")
fun customer(name: String, city: City, vararg orders: Order) = Customer(name, city, orders.toList())
fun order(vararg products: Product, isDelivered: Boolean = true) = Order(products.toList(), isDelivered)
fun shop(name: String, vararg customers: Customer) = Shop(name, customers.toList())
val shop = shop("jb test shop",
customer(lucas, Canberra,
order(reSharper),
order(reSharper, dotMemory, dotTrace)
),
customer(cooper, Canberra),
customer(nathan, Vancouver,
order(rubyMine, webStorm)
),
customer(reka, Budapest,
order(idea, isDelivered = false),
order(idea, isDelivered = false),
order(idea)
),
customer(bajram, Ankara,
order(reSharper)
),
customer(asuka, Tokyo,
order(idea)
),
customer(riku, Tokyo,
order(phpStorm, phpStorm),
order(phpStorm)
)
)
val customers: Map<String, Customer> = shop.customers.fold(hashMapOf<String, Customer>(), {
map, customer ->
map[customer.name] = customer
map
})
val orderedProducts = setOf(idea, reSharper, dotTrace, dotMemory, rubyMine, webStorm, phpStorm)
val sortedCustomers = listOf(cooper, nathan, bajram, asuka, lucas, riku, reka).map { customers[it] }
val groupedByCities = mapOf(
Canberra to listOf(lucas, cooper),
Vancouver to listOf(nathan),
Budapest to listOf(reka),
Ankara to listOf(bajram),
Tokyo to listOf(asuka, riku)
).mapValues { it.value.map { name -> customers[name] } }
Shop.kt
Kotlin
Copy
data class Shop(val name: String, val customers: List<Customer>)
data class Customer(val name: String, val city: City, val orders: List<Order>) {
override fun toString() = "$name from ${city.name}"
}
data class Order(val products: List<Product>, val isDelivered: Boolean)
data class Product(val name: String, val price: Double) {
override fun toString() = "'$name' for $price"
}
data class City(val name: String) {
override fun toString() = name
}
편집자 Jmnote 125.143.162.136 Jmnote bot
로그인하시면 댓글을 쓸 수 있습니다.