当前位置:网站首页>Scala programming (intermediate advanced experimental application)
Scala programming (intermediate advanced experimental application)
2022-07-23 21:10:00 【Brother Daning】
I talked to you earlier scala Introduction to programming , Let's share something about scala Intermediate application and code skills .
Go straight to the dry goods ~
https://blog.csdn.net/myself_ning/article/details/125945435?spm=1001.2014.3001.5501








Word frequency statistics and sorting ( example )
import java.util
import scala.collection.mutable
import scala.io.Source
object Test1 {
def main(args:Array[String]): Unit ={
// route
var path = "F:\\scala\\article.txt";
// Read data as string
var article = getArticle(path);
// Count the word frequency of the string content
articleCount(article);
}
/* Read text , Save as string */
def getArticle(path:String): String ={
var content = Source.fromFile(path).getLines().mkString
return content
}
/* Count the word frequency of the string */
def articleCount(article:String): Unit ={
// Split the article into several words
var words = article.split(" ").toList //like : List(There, are, momen ...)
// Convert words into tuples . list(my, name, is, zhangsan) ——> list((my, 1),(name, 1),(is, 1),(zhangsan, 1))
var flatMap = words.map((_, 1));
// Group tuples . Take the first character of tuple ( key ), To group .
var wordGroup = flatMap.groupBy(_._1)
// Count the The number of elements is taken as the number of word frequencies . like Map(forgotten -> 1, you,you -> 1, side -> 1, for -> 2)
var wordCount1 = wordGroup.map(x => (x._1, x._2.size))
// Sort it out . First convert to list , Then sort
var wordCount = wordCount1.toList.sortBy(_._2).reverse;
wordCount.foreach(println)
}
}
mysql AIP
// How to import jdbc Drive pack
https://blog.csdn.net/weixin_48185778/article/details/109451759?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link
// Add, delete, modify, check and develop 1
https://blog.csdn.net/weixin_48185778/article/details/109451759?spm=1001.2101.3001.6650.1&utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7ECTRLIST%7Edefault-1.no_search_link
package com.lining
package com.lining.Hotitems
import java.sql.{
Connection, DriverManager, PreparedStatement, ResultSet}
object mySql {
class MySqlTool(var ip:String= "" ,var port:String= "",var user:String= "",var passwd:String= "",var DB:String = ""){
private val url = s"jdbc:mysql://${
ip}:${
port}/${
DB}?characterEncoding=utf8&useSSL=false"
private var connection:Connection=null
private val driver = "com.mysql.jdbc.Driver"
//Connect to Mysql
def getConnection():Unit={
Class.forName(driver)
connection=DriverManager.getConnection(url,user,passwd)
println("Connect to the Database successfully!")
}
//EXECUTE
def execute(sql:String): Unit ={
val prStamt = connection.prepareStatement(sql)
prStamt.executeUpdate()
}
//INSERT.
def insert(sql:String)={
execute(sql)
}
//DELETE.
//UPDATE.
//SELECT.
def select(sql:String):Unit={
println("SQL:"+sql)
val rs: ResultSet=connection.createStatement().executeQuery(sql)
while (rs.next()){
var id = rs.getString("id")
var age = rs.getInt("cnt")
println(id+"\t"+age)
}
}
}
def main(args: Array[String]): Unit = {
val msT = new MySqlTool("139.196.237.231","3306","root","123456","test")
msT.getConnection()
val sql = "insert into tab1(id,cnt) values('a22',22);"
msT.insert(sql)
val sql2 = "select * from tab1;"
msT.select(sql2)
}
}
pgSql API
// Incomplete , Write it yourself , The general framework process is written
private var connection: Connection = null
private var ps: PreparedStatement = null
/*------------- Connect -------------- */
val driver = "org.postgresql.Driver"
val url = "jdbc:postgresql://139.196.237.231:5432/jobanalysis"
val username = "ln"
val password = "ning0852"
//1. The load driver
Class.forName(driver)
//2. Create connection
connection = DriverManager.getConnection(url, username, password)
/*------------- perform -------------- */
val sql = s"insert into job_data(name,work_link,price,city) values('${
value.name}','${
value.workLink}','${
value.price}','${
value.city}'');"
ps = connection.prepareStatement(sql)
ps.executeUpdate()
/*------------- close -------------- */
ps.close()
connection.close()
class PgTool(var ip:String= "139.196.237.231" ,
var port:String= "5432",
var user:String= "ln",
var passwd:String= "ning0852",
var DB:String = "jobanalysis"){
private var connection: Connection = null
private var ps: PreparedStatement = null
private val driver = "org.postgresql.Driver"
private val url = s"jdbc:postgresql://${
ip}:${
port}/${
DB}"
// Connect
def getConnection():Unit={
//1. The load driver
Class.forName(driver)
//2. Create connection
connection=DriverManager.getConnection(url,user,passwd)
println("Connect to the Database successfully!")
}
// disconnect
def close():Unit={
connection.close()
println(" Database connection closed ...")
}
//SELECT
def select(sql:String):List[String]={
// Exhibition sql
println("SQL:"+sql)
val rs: ResultSet=connection.createStatement().executeQuery(sql)
val workNameList = ListBuffer[String]()
while (rs.next()){
workNameList += rs.getString("class")
workNameList += rs.getString("name")
}
workNameList.toList
}
}
scattered
scala Read the file
Read csv
import scala.io.Source
val sourceFile = Source.fromFile(" File path "," code ")
for(i <- sourceFile.getLines){
println(i);
}
String.split() function
https://www.cnblogs.com/davidhaslanda/p/4050471.html
Commonly used :
S.split(" Separator ",-1)
Input
object compute {
def main(args: Array[String]): Unit = {
import scala.io.StdIn
// Scala Read data from the console
println("name")
val name = StdIn.readLine()
println("age")
val age = StdIn.readInt()
println("salary")
val salary = StdIn.readDouble()
//Java from The console reads data
System.out.println("name")
val scanner= new Scanner(System.in)
val nameJ= scanner.next()
System.out.println("age")
val ageJ = scanner.next()
System.out.println("salary")
val salaryJ = scanner.next()
}
}
There is judgment 【.contains() .exists()】
// Study
https://blog.csdn.net/power0405hf/article/details/50371438
val m=Map(1 -> 1, 2 -> 2, 3 -> 3, 4 -> 4)
// m: scala.collection.immutable.Map[Int,Int]= Map(1 -> 1, 2 -> 2, 3 -> 3, 4-> 4)
val l = List(1,2,3,4)
// l:List[Int] = List(1,2,3,4)
val v = Vector(1,2,3,4)
// v: scala.collection.immutable.Vector[Int] = Vector(1,2,3,4)
val S = "12345"
m.exists(_._1 == 3) //> res0: Boolean = true
m.contains(3) //> res1: Boolean = true
l.exists(_ == 3) //> res2: Boolean = true
l.contains(3) //> res3: Boolean = true
v.exists(_ == 3) //> res4: Boolean = true
v.contains(3) //> res5: Boolean = true
S.contains(3) //> res6: Boolean = true
[ Failed to transfer the external chain picture , The origin station may have anti-theft chain mechanism , It is suggested to save the pictures and upload them directly (img-Ov836vQ8-1658547643165)(scala.assets/image-20211228150811358.png)]
doubt — answer
1. Why? main The method must be written in object in ?
/* The program must take a function main As an entrance , But because there is no global function , So it must be written in the class , And it is not entered through object calls , So if it's static , but scala No, static This keyword and this semantics , So again obejct Companion objects, this kind of thing . Semantically, it is the instance method of the associated singleton object , It feels more object-oriented , Follow java/C#( Are not purely object-oriented ) That's different .C++ Multiple paradigm , You can define global functions , therefore main Just direct the global function , There is no need to go around this bend . The official answer is : scala and Java equally , If you want to run a program , There has to be one main Method . And in the Java in main The method is static , And in the scala No static methods in . stay scala in , This main Methods must be placed in a singleton object .( and scala Single column objects in object Is similar to java in object.) 2. Immutable list 、 Set 、 Array … etc. . Don't you mean immutable ? Why are there some operations ? Such as splicing …
/* answer : Yes . When doing some operations on immutable types , It is not operated on the original variable , Instead, generate a new variable . */
// List List together , Make a new one List
scala> val b = List(1, 2, 3) ++ List(1, 2, 3)
b: List[Int] = List(1, 2, 3, 1, 2, 3)
scala> b
res8: List[Int] = List(1, 2, 3, 1, 2, 3)
//Set Set addition operation , Generate a new set
scala> Set(1,2,3,4,5,6) ++ Set(6,7,8)
res13: scala.collection.immutable.Set[Int] = Set(5, 1, 6, 2, 7, 3, 8, 4)
/* Sum up , It can be seen that , This immutable type Even if there is operation , That is also generating a new variable , The content of the original variable will not be modified */
3. Variable type references
// Immutable types are immutable In the library , By default, it has been referenced . If you want to reference variable types , You need to quote mutable library .
import scala.collection.immutable.xxxxx
import scala.collection.mutable.xxxx
// as follows Examples show Immutable set And Operation of variable sets .【 Pay attention to the following 】
//1. The default reference is an immutable set
//2. Variable sets are created in the same way as immutable sets , Just need to import in advance mutable.set Variable set class
//3. Immutable types cannot be modified during operation , Variable types can .
scala> val a = Set(1,2,3,4)
a: scala.collection.immutable.Set[Int] = Set(1, 2, 3, 4)
scala> a += 1
<console>:13: error: value += is not a member of scala.collection.immutable.Set[Int]
a += 1
^
scala> import scala.collection.mutable.Set
import scala.collection.mutable.Set
scala> val b = Set(1,2,3,4)
b: scala.collection.mutable.Set[Int] = Set(1, 2, 3, 4)
scala> b += 1
res21: b.type = Set(1, 2, 3, 4)
scala> import scala.collection.immutable.Set
import scala.collection.immutable.Set
scala> val c = Set(1,2,3,4)
<console>:13: error: reference to Set is ambiguous;
it is imported twice in the same scope by
import scala.collection.immutable.Set
and import scala.collection.mutable.Set
val c = Set(1,2,3,4)
4. Instance members 、 Static members
/* answer 1: Static members categorize all , Instance members belong to the object ! answer 2: JAVA Can include 2 Species : Instance members and class members ( Static members ) Instance member belongs to the object , Instance members include member variables and instance member methods . Only after the object is created , To access instance member variables and call instance member methods through objects . Class member belongs to class , Class members need keywords static Mark , Also known as static members , Class members include class member variables and class member methods . Through the class name, you can directly access class member variables and call class member methods , Even if no objects are created , You can also reference class members . Class members can also be referenced by objects . answer 3: */
thus ,scala This is the end of intermediate simple learning .
.
.
.
Blood stained paintings of rivers and mountains ,
How can I defeat you with a little cinnabar ,
Lose the world ,
It's always just a bustling .
边栏推荐
- STM32c8t6驱动激光雷达(一)
- 剑指 Offer II 115. 重建序列 : 拓扑排序构造题
- Vrrp+mstp configuration details [Huawei ENSP experiment]
- 深入浅出边缘云 | 1. 概述
- Major upgrade of openim - group chat reading diffusion model release group management function upgrade
- Qt桌面白板工具其一(解决曲线不平滑的问题——贝塞尔曲线)
- [wechat applet] do you know about applet development?
- Himawari-8 data introduction and download method
- 做一个有职业操守的软件匠人
- LeetCode热题 HOT52-100
猜你喜欢

Addon plug-in 002 of CDR plug-in development - write an EXE program that can be run by double clicking in 1 minute

Stm32c8t6 driven lidar (I)

【攻防世界WEB】难度四星12分进阶题:FlatScience

High numbers | calculation of triple integral 2 | high numbers | handwritten notes
现在完全不知道怎么同步

对接湖南CA使用U_KEY登录

LU_ASR01语音模块使用

High numbers | calculation of double integral 3 | high numbers | handwritten notes

VLAN综合实验

Opencv image processing Laplace pyramid
随机推荐
最小生成树:Prim
[kernel] platform bus model for driving development and learning
支付宝常用接口统一封装,可直接支付参数使用(适用于H5、PC、APP)
比较关注证券公司究竟哪个佣金最低?请问网上开户安全么?
【微信小程序】你了解小程序开发吗?
Car rental vehicle management system based on jsp+ssm+mysql car rental
【创建 Birthday Card 应用】
高数下|二重积分的计算3|高数叔|手写笔记
Preprocessing tropomi (sentinel 5p) data with envi
Major optimization of openim - Message loading on demand, consistent cache, uniapp Publishing
LU_ASR01语音模块使用
Ssm+mysql to realize snack mall system (e-commerce shopping)
How to get the worker's hat? Where is the worker's helmet?
Today's sleep quality record 81 points
高数下|二重积分的计算2|高数叔|手写笔记
ES6 feature: Promise (custom encapsulation)
Vrrp+mstp configuration details [Huawei ENSP experiment]
ES6特性:Promise(自定义封装)
STM32C8t6 驱动激光雷达实战(二)
VLAN综合实验