Skip to content

Commit a53c280

Browse files
committed
使用Stream对list的一些操作
1 parent 7d2f675 commit a53c280

File tree

2 files changed

+57
-3
lines changed

2 files changed

+57
-3
lines changed

pom.xml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,13 @@
1919
</plugin>
2020
</plugins>
2121
</build>
22+
<dependencies>
23+
<dependency>
24+
<groupId>com.hynnet</groupId>
25+
<artifactId>json-lib</artifactId>
26+
<version>2.4</version>
27+
</dependency>
28+
</dependencies>
2229

2330

2431
</project>

src/main/java/com/xu/java8/Stream/Streams6.java

Lines changed: 50 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
package com.xu.java8.Stream;
22

3-
import java.util.HashMap;
4-
import java.util.LinkedHashMap;
5-
import java.util.Map;
3+
import net.sf.json.JSONObject;
4+
5+
import java.util.*;
66

77
/**
88
* Created by xu on 2016/9/13.
@@ -22,6 +22,53 @@ public static void main(String args[]) {
2222
unsortMap.put("m", 2);
2323
unsortMap.put("f", 9);
2424
System.out.println(sortByValue(unsortMap));
25+
26+
/**
27+
* 对list里面的json处理
28+
*/
29+
List<Object> list = new ArrayList<>();
30+
JSONObject data1 = new JSONObject();
31+
data1.put("type", "支出");
32+
data1.put("money", 500);
33+
JSONObject data2 = new JSONObject();
34+
data2.put("type", "收入");
35+
data2.put("money", 1000);
36+
JSONObject data3 = new JSONObject();
37+
data3.put("type", "借贷");
38+
data3.put("money", 100);
39+
list.add(data1);
40+
list.add(data2);
41+
list.add(data3);
42+
/**
43+
* 按money的值来排列json
44+
*/
45+
list.stream()
46+
.filter(x -> JSONObject.fromObject(x).containsKey("money"))
47+
.sorted((b, a) -> Integer.valueOf(JSONObject.fromObject(a).getInt("money")).compareTo(JSONObject.fromObject(b)
48+
.getInt("money")))
49+
.forEach(System.out::println);
50+
/**
51+
* 找到最小的money
52+
*/
53+
Integer min=list.stream()
54+
.filter(x -> JSONObject.fromObject(x).containsKey("money"))
55+
.map(x->JSONObject.fromObject(x).getInt("money"))
56+
.sorted()
57+
.findFirst()
58+
.get();
59+
System.out.println(min);
60+
/**
61+
* 计算type的数目
62+
*/
63+
Map<String, Integer> type_count = new HashMap<>();
64+
list.stream()
65+
.filter(x -> JSONObject.fromObject(x).containsKey("type"))
66+
.map(x -> JSONObject.fromObject(x).getString("type"))
67+
.forEach(x -> {
68+
if (type_count.containsKey(x)) type_count.put(x.toString(), type_count.get(x) + 1);
69+
else type_count.put(x.toString(), 1);
70+
});
71+
System.out.println(type_count.toString());
2572
}
2673

2774
/**

0 commit comments

Comments
 (0)