欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Groovy集合类与迭代 博客分类: Groovy GroovyJavaJavaScriptSQL ServerF# 

程序员文章站 2024-02-21 20:19:16
...

集合类
// List String StringBuffer Range Map File Matcher统一使用size方法获取长度
def toys=[['a','01'],['b','02'],['c','03']]
assert toys instanceof ArrayList

println toys[1]
println toys.get(1)
println toys[1..<2]
toys[2] = ['3','03']
println toys[-1]       // 倒数第一个
toys.putAt 1, ['2','02']
println toys[1]

toys<<['4','04']  // 追加元素
println toys[-1]

toys2 = toys + [4,5] // 连接元素
println toys2

def toy8 =[]
toy8 << '11'
toy8 << '22'
println toy8
toy8 << ['a','b']
println toy8

// 有些方法会修改原列表,有些方法不修改原列表
def list = [1,2,3,[4,5]]
println list.flatten(); //展开后返回新列表
println list.intersect([3,4,5]) //求交集
println list.pop();//删除列表最后元素
println list.reverse() //反转列表,返回新列表
println list.sort();
def list2 = [1,2,3,4,2]
println list2.count(2)

// Groovy 反射
def s = "hello"
println s
println s.class
["Java", "Groovy", "JavaScript"].each{println it}
s.class.methods.each{println it}


def map = [:]
assert map instanceof LinkedHashMap
assert map.size() == 0
map = [1:'toy1',2:'toy2']
assert map.containsKey(1)
assert map.containsValue('toy1')
println map
println map[2]

def map1 = ["java":"server", "groovy":"server", "javascript" : "web"]
// 从 map 获得键和值
map1.each { toy -> println toy.key + ':' + toy.value }
map1.each{
	print it.key
	println it.value
}
map1.each{k,v->
	print k
	println v
}
// 获得 map 值
print map1.java

//Groovy map.class 返回的是map中key为class 的元素 getClass才是返回类型
println ["Java", "Groovy", "JavaScript"].class
// java.util.ArrayList
def map2 = ["Java":"server", "Groovy":"server", "JavaScript":"web"]
println map.class
// null
map2.class = "I am a map element"
println map2.class
// I am a map element
println map2.getClass()
// class java.util.LinkedHashMap


def range = 1..<5
println range
println range.class
assert range instanceof List
range = 'a'..<'e'
println range
println range.class
range = 5..1
println range
println range.size();
println range.contains(2)
println range.getFrom();
println range.getTo()
println range.isReverse()
println range.subList(2,3)



for each迭代
// String迭代
def name = "xace"
name.each{
	print it + " "  //x a c e
}

//Range迭代
def range = 5..10
range.each{print it}

// Date 迭代
def today = new Date()
def nextWeek = today + 7
(today..nextWeek).each{
	println it
}

// 枚举迭代
enum DAY{
  MONDAY, TUESDAY, WEDNESDAY, THURSDAY,
    FRIDAY, SATURDAY, SUNDAY
}
DAY.each{
  println it
}
(DAY.MONDAY..DAY.FRIDAY).each{
  println it
}

//ResultSet 迭代
import groovy.sql.*

def sql = Sql.newInstance(
        "jdbc:mysql://localhost:3306/test",
        "root",
        "root",
        "com.mysql.jdbc.Driver"
)
sql.eachRow("select username from user_info"){row->
  println row.username
}

sql.eachRow("select * from user_info"){
  println("name : ${it.username}")
  println("age  : ${it.age}")
}

//文件迭代
def f = new File("D:\\新建文本文档.txt")
f.eachLine{con->
  println "this file content is ${con} "
}

// 分解文件的每一行 拆成单词
def f = new File("D:\\新建文本文档.txt")
f.splitEachLine(" "){words->
  words.each{ println it }
}


// 目录迭代 分离文件和目录
def dir = new File(".")
dir.eachFile{file->
  if(file.isFile()){
    println "FILE: ${file}"
  }else if(file.isDirectory()){
    println "DIR:  ${file}"
  }else{
    println "Uh, I'm not sure what it is..."
  }
}

// 三元操作符版
def f = new File(".")
f.eachFile{file->
  println file.isFile() ? "file : ${file}" : "dir : ${file}"
}
// 如果只对目录有兴趣,那么可以使用 eachDir() 而不是 eachFile()。
// 还提供了 eachDirMatch() 和 eachDirRecurse() 方法。

// URL 迭代
def url = new URL("http://www.sina.com")
url.eachLine{line->
  println line
}
"http://www.ibm.com".toURL().eachLine{ println it }