Fork me on GitHub

Java、Groovy、JavaScript、Python各语言对比

Get start

Java

1
2
3
4
5
public class Client {
public static void main(String[] args){
System.out.println("Hello, world.");
}
}

Groovy

1
2
3
static void main(String[] args) {
println('Hello, world.')
}

JavaScript

1
console.log("Hello, world.");

Python

1
2
if __name__ == '__main__':
print('Hello, world.')

字符串

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Client {
public static void main(String[] args) {
String a = "Hello";
// 截取 (Hel)
System.out.println(a.substring(0, 3));
// 转化 (123)
System.out.println(String.valueOf(123));
// 拼接 (Hello, world.)
System.out.println(a + ", world.");
// 格式化 (Hello, I am 10.)
System.out.println(String.format("%s, I am %d.", a, 10));
}
}

Groovy

1
2
3
4
5
6
7
8
9
10
11
static void main(String[] args) {
def a = "Hello"
// 截取 (Hel)
println(a[0..3])
// 转化 (123)
println(String.valueOf(123));
// 拼接 (Hello, world.)
println(a + ", world.")
// 格式化 (Hello, I am 10.)
println("${a}, I am ${10}.")
}

JavaScript

1
2
3
4
5
6
7
8
9
let a = "Hello";
// 截取 (Hel)
console.log(a.substr(0, 3));
// 转化 (123)
console.log(String(123));
// 拼接 (Hello, world.)
console.log(a + ", world.");
// 格式化 (Hello, I am 10.)
console.log(`${a}, I am ${10}.`);

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
# coding=utf-8
if __name__ == '__main__':
a = "Hello"
# 截取 (Hel)
print(a[0:3])
# 转化 (123)
print(str(123))
# 拼接 (Hello, world.)
print(a + ", world.")
# 格式化 (Hello, I am 10.)
print("%s, I am %d." % (a, 10))
# or
print("{}, I am {}.".format(a, 10))

时间格式化

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Client {
public static void main(String[] args) {
// 当前时间戳 (1532955845305)
long currentTimeMillis = System.currentTimeMillis();
System.out.println(currentTimeMillis);

// 格式化处理 (2018-07-30 21:04:05)
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime now = LocalDateTime.now();
String format = formatter.format(now);
System.out.println(format);
}
}

Groovy

1
2
3
4
5
6
7
8
9
10
11
static void main(String[] args) {
// 当前时间戳 (1532956684952)
def currentTimeMillis = System.currentTimeMillis()
println(currentTimeMillis)

// 格式化处理 (2018-07-30 21:18:05)
def formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
def now = LocalDateTime.now()
def format = formatter.format(now)
println(format)
}

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// 当前时间戳 (1532956509000)
let currentTimeMillis = Date.parse(new Date());
console.log(currentTimeMillis);

// 格式化处理 (2018-07-30 21:15:09)
Date.prototype.Format = function (fmt) {
let o = {
"M+": this.getMonth() + 1, // 月
"d+": this.getDate(), // 日
"h+": this.getHours(), // 时
"m+": this.getMinutes(), // 分
"s+": this.getSeconds(), // 秒
"q+": Math.floor((this.getMonth() + 3) / 3), // 季度
"S": this.getMilliseconds() // 毫秒
};
if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
for (let k in o)
if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
return fmt;
};
let format = new Date().Format("yyyy-MM-dd hh:mm:ss");
console.log(format);

Python

1
2
3
4
5
6
7
8
9
10
import time
import datetime

if __name__ == '__main__':
# 当前时间戳 (1532957083)
print(int(round(time.time())))

# 格式化处理 (2018-07-30 21:24:43)
format = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print(format)

函数

Java

1
2
3
4
5
6
7
8
9
10
public class Client {
public static void main(String[] args) {
int result = plus(1, 2);
System.out.println(result);
}

private static int plus(int a, int b) {
return a + b;
}
}

Groovy

1
2
3
4
5
6
7
8
9
static void main(String[] args) {
def result = plus 1, 2
println(result)
}

static def plus(int a, int b) {
// 最后一行return可省略
return a + b
}

JavaScript

1
2
3
4
5
6
function plus(a, b) {
return a + b;
}

let result = plus(1, 2);
console.log(result);

Python

1
2
3
4
5
6
def plus(a=0, b=0):
return a + b

if __name__ == '__main__':
result = plus(1, 2)
print(result)

列表

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class Client {
public static void main(String[] args) {
// 新建
List<String> list = new ArrayList<>();
// 添加
list.add("a");
list.add("b");
list.add("c");
// 移除
list.remove("c");
// 查询
String first = list.get(0);

// 拼接
List<String> added = Arrays.asList("m", "n");
list.addAll(added);

// 遍历
for (String s : list) {
System.out.println(s);
}
}
}

Groovy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
static void main(String[] args) {
// 新建 & 添加
def list = ['a', 'b']
// 添加
list << 'c'
// 移除
list -= 'c'
// 查询
def first = list[0]

// 拼接
def added = ['m', 'n']
list += added
// [a, b, m, n]
println(list)

// 遍历
for (i in list) {
println(i)
}
// or
list.each {
println(it)
}
}

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// 新建 & 添加
let list = ['a', 'b'];
// 添加
list.push('c');
// 移除
list = list.filter(s => s !== 'c');
// 查询
let first = list[0];

// 拼接
let added = ['m', 'n'];
list = [...list, ...added];
// or
// list = list.concat(added);
// [a, b, m, n]
console.log(list);

// 遍历
for (let i = 0; i < list.length; i++) {
console.log(list[i]);
}

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# coding=utf-8

if __name__ == '__main__':
# 新建 & 添加
list = ['a', 'b']
# 添加
list.append('c')
# 移除
del list[2]
# or
# list.remove('c')
print(list)
# 查询
first = list[0]

# 拼接
added = ['m', 'n']
list = list + added
# or
# list = list.extend(added)
# [a, b, m, n]
print(list)

# 遍历
for i in list:
print(i)

字典

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class Client {
public static void main(String[] args) {
// 新建
Map<String, Integer> map = new HashMap<>();
// 添加
map.put("a", 1);
map.put("b", 2);
map.put("c", 3);
// 移除
map.remove("c");
// 查询
Integer first = map.get("a");

// 拼接
Map<String, Integer> added = new HashMap<>();
added.put("m", 4);
added.put("n", 5);
map.putAll(added);

// 遍历
map.forEach((key, value) -> {
System.out.println(key + ": " + value);
});
}
}

Groovy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
static void main(String[] args) {
// 新建 & 添加
def map = ['a': 1, 'b': 2]
// 添加
map['c'] = 3
// 移除
map.remove('c')
// 查询
Integer first = map.get('a')

// 拼接
def added = ['m': 4, 'n': 5]
map += added

// 遍历
map.each {
println(it.key + ': ' + it.value)
}
}

JavaScript

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 新建 & 添加
let map = {'a': 1, 'b': 2};
// 添加
map['c'] = 3;
// 移除
delete map['c'];
// 查询
let first = map['a'];

// 拼接
let added = {'m': 4, 'n': 5};
map = {...map, ...added};
console.log(map);

// 遍历
for (let key in map) {
if (map.hasOwnProperty(key)) {
console.log(`${key}: ${map[key]}`);
}
}

Python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# coding=utf-8

if __name__ == '__main__':
# 新建 & 添加
map = {'a': 1, 'b': 2}
# 添加
map['c'] = 3
# 移除
del map['c']
# 查询
first = map['a']

# 拼接
added = {'m': 4, 'n': 5}
map.update(added)
print(map)

# 遍历
for key, value in map.items():
print('%s: %s' % (key, value))

文件

Java

1
2
3
4
5
6
7
public class Client {
public static void main(String[] args) throws IOException {
File file = new File("/Users/puke/Desktop/TODO.md");
String content = Files.readFile(file);
System.out.println(content);
}
}

Groovy

1
2
3
4
5
static void main(String[] args) {
def file = new File("/Users/puke/Desktop/TODO.md")
def content = file.text
println(content)
}

Python

1
2
3
4
if __name__ == '__main__':
with open("/Users/puke/Desktop/TODO.md") as f:
content = f.read()
print(content)

网络

Java

1
2
3
4
5
6
7
8
public class Client {
public static void main(String[] args) throws IOException {
String url = "https://www.baidu.com";
InputStream inputStream = new URL(url).openStream();
String content = Files.readFile(inputStream);
System.out.println(content);
}
}

Groovy

1
2
3
4
5
static void main(String[] args) {
def url = "https://www.baidu.com"
def content = new URL(url).openStream().text
println(content)
}

Python

1
2
3
4
5
6
7
import urllib2

if __name__ == '__main__':
url = "https://www.baidu.com"
response = urllib2.urlopen(url)
content = response.read()
print(content)

------------- The end -------------