scala 转换、过滤、分组、排序
1)为集合中元素,添加前缀Int)=>{(2)flatMap()扁平化。
·
文章目录
前言
1. map() 将集合内元素按照规则进行转换
(1)为集合中元素,添加前缀
val list = List(1, 2, 4, 9, 3)
val list1 = list.map((num: Int) => {
"00000"+num
})
println(list1.mkString(","))
(2)flatMap()扁平化
val source = Source.fromFile("data/word.txt")
val list = source.getLines().toList
source.close()
val words = list.flatMap(line => line.split(" "))
println(words)
2. filter() 根据指定的规则对集合内元素进行筛选过滤
val list = List(1, 2, 4, 9, 3)
val list2 = list.filter(num => num % 2 == 1)
println(list2.mkString(","))
3. groupBy() 按照指定的规则对数据进行分组
val list = List(1, 2, 4, 9, 3)
val list3 = list.groupBy(num => num % 3)
println(list3.mkString(","))
4. sortBy() 按照指定的规则对集合的数据进行排序
(1)默认规则为升序,对于字符串采用字典序排序
val list5 = List(1, 4, 3, 2)
val list6 = list5.sortBy(num => num)
println(list6)
val list7 = List("1", "111", "2", "3", "22")
val list8 = list7.sortBy(str => str)
println(list8)
val list9 = list7.sortBy(str => str.toInt)
println(list9)
(2)需要使用降序,可传递第二个参数列表Ordering.Int.reverse
val list5 = List(1, 4, 3, 2)
val list10 = list5.sortBy(num => num)(Ordering.Int.reverse)
println(list10)
(3)对象排序
scala的元组,默认按照第一个排序,第一个相同时,按照第二个排序,依次类推
先按照年龄排序(从小到大),再按照薪水排序(从大到小)
package com.cz.part7
object T23 {
def main(args: Array[String]): Unit = {
val user1 = new User
user1.name = "cz"
user1.age = 18
user1.sal = 8000
val user2 = new User
user2.name = "fd"
user2.age = 39
user2.sal = 10000
val user3 = new User
user3.name = "fe"
user3.age = 5
user3.sal = 20000
val user4 = new User
user4.name = "iop"
user4.age = 18
user4.sal = 7000
val users: List[User] = List(user1, user2, user3, user4)
val users1 = users.sortBy((user: User) => (user.age, user.sal))(Ordering.Tuple2(Ordering.Int, Ordering.Int.reverse))
println(users1)
}
class User {
var age: Int = _
var name: String = _
var sal: Int = _
override def toString: String = s"age:$age name:$name sal:$sal"
}
}
(4)sortWith()
自定义排序
val users2 = users.sortWith(
(left, right) => {
if (left.age < right.age) {
true
} else if (left.age == right.age) {
left.sal > right.sal
} else {
false
}
}
)
println(users2)
更多推荐
已为社区贡献7条内容
所有评论(0)