|
| 1 | +##Stream类 |
| 2 | + |
| 3 | +java.util.Stream 表示能应用在一组元素上一次执行的操作序列。 |
| 4 | +Stream 操作分为中间操作或者最终操作两种,最终操作返回一特定类型的计算结果, |
| 5 | +而中间操作返回Stream本身,这样你就可以将多个操作依次串起来。Stream 的 |
| 6 | +创建需要指定一个数据源,比如 java.util.Collection的子类,List或者Set, |
| 7 | +Map不支持。Stream的操作可以串行执行或者并行执行。 |
| 8 | +- **Stream的基本接口** |
| 9 | +``` |
| 10 | + List<String> stringCollection = new ArrayList<>(); |
| 11 | + stringCollection.add("ddd2"); |
| 12 | + stringCollection.add("aaa2"); |
| 13 | + stringCollection.add("bbb1"); |
| 14 | + stringCollection.add("aaa1"); |
| 15 | + stringCollection.add("bbb3"); |
| 16 | + stringCollection.add("ccc"); |
| 17 | + stringCollection.add("bbb2"); |
| 18 | + stringCollection.add("ddd1"); |
| 19 | +``` |
| 20 | +####Filter 过滤. |
| 21 | + |
| 22 | +Filter通过一个predicate接口来过滤并只保留符合条件的元素,该操作属于中间操作, |
| 23 | +所以我们可以在过滤后的结果来应用其他Stream操作(比如forEach)。forEach |
| 24 | +需要一个函数来对过滤后的元素依次执行。forEach是一个最终操作,所以我们不 |
| 25 | +能在forEach之后来执行其他Stream操作。 |
| 26 | +``` |
| 27 | + stringCollection |
| 28 | + .stream() |
| 29 | + .filter((s) -> s.startsWith("a")) |
| 30 | + .forEach(System.out::println); |
| 31 | +``` |
| 32 | +####Sorted 排序. |
| 33 | + |
| 34 | +Sorted是一个中间操作,返回的是排序好后的Stream。如果你不指定一个自定义的Comparator则会使用默认排序. |
| 35 | +``` |
| 36 | + stringCollection |
| 37 | + .stream() |
| 38 | + .sorted() |
| 39 | + .forEach(System.out::println); |
| 40 | + System.out.println(stringCollection);//原数据源不会被改变 |
| 41 | +``` |
| 42 | +####Map |
| 43 | + |
| 44 | +中间操作map会将元素根据指定的Function接口来依次将元素转成另外的对象. |
| 45 | +``` |
| 46 | + stringCollection |
| 47 | + .stream() |
| 48 | + .map(String::toUpperCase) |
| 49 | + .map((s)->s+" space") |
| 50 | + .sorted((a, b) -> b.compareTo(a)) |
| 51 | + .forEach(System.out::println); |
| 52 | +``` |
| 53 | +####Match |
| 54 | + |
| 55 | +Stream提供了多种匹配操作,允许检测指定的Predicate是否匹配整个Stream。 |
| 56 | +所有的匹配操作都是最终操作,并返回一个boolean类型的值。 |
| 57 | +``` |
| 58 | + boolean anyStartsWithA = stringCollection |
| 59 | + .stream() |
| 60 | + .anyMatch((s) -> s.startsWith("a")); |
| 61 | + System.out.println(anyStartsWithA); // true |
| 62 | +
|
| 63 | + boolean allStartsWithA = stringCollection |
| 64 | + .stream() |
| 65 | + .allMatch((s) -> s.startsWith("a")); |
| 66 | + System.out.println(allStartsWithA); // false |
| 67 | +
|
| 68 | + boolean noneStartsWithZ = stringCollection |
| 69 | + .stream() |
| 70 | + .noneMatch((s) -> s.startsWith("z")); |
| 71 | + System.out.println(noneStartsWithZ); // true |
| 72 | +``` |
| 73 | +####Count |
| 74 | + |
| 75 | +计数是一个最终操作,返回Stream中元素的个数,返回值类型是long。 |
| 76 | +``` |
| 77 | + long startsWithB = stringCollection |
| 78 | + .stream() |
| 79 | + .filter((s) -> s.startsWith("b")) |
| 80 | + .count(); |
| 81 | + System.out.println(startsWithB); // 3 |
| 82 | +``` |
| 83 | +####Reduce |
| 84 | + |
| 85 | +Reduce是一个最终操作,允许通过指定的函数来讲stream中的多个元素规约为一个元素,规约后的结果是通过Optional接口表示的。 |
| 86 | +``` |
| 87 | + Optional<String> reduced = |
| 88 | + stringCollection |
| 89 | + .stream() |
| 90 | + .sorted() |
| 91 | + .reduce((s1, s2) -> s1 + "#" + s2); |
| 92 | +
|
| 93 | + reduced.ifPresent(System.out::println); |
| 94 | + ##:aaa1#aaa2#bbb1#bbb2#bbb3#ccc#ddd1#ddd2 |
| 95 | +``` |
| 96 | +- **并行stream和串行stream** |
| 97 | +####并行stream |
| 98 | + |
| 99 | +``` |
| 100 | + List<String> values = new ArrayList<>(MAX); |
| 101 | + for (int i = 0; i < MAX; i++) { |
| 102 | + UUID uuid = UUID.randomUUID(); |
| 103 | + values.add(uuid.toString()); |
| 104 | + } |
| 105 | +
|
| 106 | + long t0 = System.nanoTime(); |
| 107 | + long count = values.stream().sorted().count(); |
| 108 | + System.out.println(count); |
| 109 | +
|
| 110 | + long t1 = System.nanoTime(); |
| 111 | + long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); |
| 112 | + System.out.println(String.format("sequential sort took: %d ms", millis)); |
| 113 | +``` |
| 114 | +####串行stream |
| 115 | + |
| 116 | +串行stream是在运行时将数据划分成了多个块,然后将数据块分配给合适的处理器去处理。 |
| 117 | +只有当所有块都处理完成了,才会执行之后的代码。 |
| 118 | + |
| 119 | +``` |
| 120 | + List<String> values = new ArrayList<>(MAX); |
| 121 | + for (int i = 0; i < MAX; i++) { |
| 122 | + UUID uuid = UUID.randomUUID(); |
| 123 | + values.add(uuid.toString()); |
| 124 | + } |
| 125 | + |
| 126 | + long t0 = System.nanoTime(); |
| 127 | + long count = values.parallelStream().sorted().count(); |
| 128 | + System.out.println(count); |
| 129 | +
|
| 130 | + long t1 = System.nanoTime(); |
| 131 | + long millis = TimeUnit.NANOSECONDS.toMillis(t1 - t0); |
| 132 | + System.out.println(String.format("parallel sort took: %d ms", millis)); |
| 133 | +``` |
| 134 | +时间结果比较: |
| 135 | +``` |
| 136 | +1000000 |
| 137 | +sequential sort took: 717 ms |
| 138 | +1000000 |
| 139 | +parallel sort took: 303 ms |
| 140 | +``` |
| 141 | +- **IntStream接口** |
| 142 | + |
| 143 | +IntStream接口是stream的一种,继承了BaseStream接口。 |
| 144 | +####range |
| 145 | +``` |
| 146 | + IntStream.range(0, 10) |
| 147 | + .forEach(i -> { |
| 148 | + if (i % 2 == 1) System.out.print(i+" "); |
| 149 | + }); |
| 150 | + ##:1 3 5 7 9 |
| 151 | + |
| 152 | + OptionalInt reduced1 = |
| 153 | + IntStream.range(0, 10) |
| 154 | + .reduce((a, b) -> a + b); |
| 155 | + System.out.println(reduced1.getAsInt()); |
| 156 | + |
| 157 | + int reduced2 = |
| 158 | + IntStream.range(0, 10) |
| 159 | + .reduce(7, (a, b) -> a + b); |
| 160 | + System.out.println(reduced2); |
| 161 | + ##:45 |
| 162 | + 52 |
| 163 | +``` |
| 164 | +####sum |
| 165 | +``` |
| 166 | + System.out.println(IntStream.range(0, 10).sum()); |
| 167 | +``` |
| 168 | +- **Stream的应用** |
| 169 | +``` |
| 170 | + Map<String, Integer> unsortMap = new HashMap<>(); |
| 171 | + unsortMap.put("z", 10); |
| 172 | + unsortMap.put("b", 5); |
| 173 | + unsortMap.put("a", 6); |
| 174 | + unsortMap.put("c", 20); |
| 175 | + unsortMap.put("d", 1); |
| 176 | + unsortMap.put("e", 7); |
| 177 | + unsortMap.put("y", 8); |
| 178 | + unsortMap.put("n", 99); |
| 179 | + unsortMap.put("j", 50); |
| 180 | + unsortMap.put("m", 2); |
| 181 | + unsortMap.put("f", 9); |
| 182 | +``` |
| 183 | +使用stream类来对map的value排序 |
| 184 | +``` |
| 185 | + public static <K, V extends Comparable<? super V>> Map<K, V> sortByValue(Map<K, V> map) { |
| 186 | + Map<K, V> result = new LinkedHashMap<>(); |
| 187 | + map.entrySet().parallelStream() |
| 188 | + .sorted((o1, o2) -> (o2.getValue()).compareTo(o1.getValue())) |
| 189 | + .forEachOrdered(x -> result.put(x.getKey(), x.getValue())); |
| 190 | + return result; |
| 191 | + } |
| 192 | + System.out.println(sortByValue(unsortMap)); |
| 193 | + ##:{n=99, j=50, c=20, z=10, f=9, y=8, e=7, a=6, b=5, m=2, d=1} |
| 194 | +``` |
| 195 | +``` |
| 196 | + List<Object> list = new ArrayList<>(); |
| 197 | + JSONObject data1 = new JSONObject(); |
| 198 | + data1.put("type", "支出"); |
| 199 | + data1.put("money", 500); |
| 200 | + JSONObject data2 = new JSONObject(); |
| 201 | + data2.put("type", "收入"); |
| 202 | + data2.put("money", 1000); |
| 203 | + JSONObject data3 = new JSONObject(); |
| 204 | + data3.put("type", "借贷"); |
| 205 | + data3.put("money", 100); |
| 206 | + list.add(data1); |
| 207 | + list.add(data2); |
| 208 | + list.add(data3); |
| 209 | +``` |
| 210 | +使用stream类来处理list里面的json数据 |
| 211 | +``` |
| 212 | + /** |
| 213 | + * 按money的值来排列json |
| 214 | + */ |
| 215 | + list.stream() |
| 216 | + .filter(x -> JSONObject.fromObject(x).containsKey("money")) |
| 217 | + .sorted((b, a) -> Integer.valueOf(JSONObject.fromObject(a).getInt("money")).compareTo(JSONObject.fromObject(b) |
| 218 | + .getInt("money"))) |
| 219 | + .forEach(System.out::println); |
| 220 | + /** |
| 221 | + * 找到最小的money |
| 222 | + */ |
| 223 | + Integer min = list.stream() |
| 224 | + .filter(x -> JSONObject.fromObject(x).containsKey("money")) |
| 225 | + .map(x -> JSONObject.fromObject(x).getInt("money")) |
| 226 | + .sorted() |
| 227 | + .findFirst() |
| 228 | + .get(); |
| 229 | + System.out.println(min); |
| 230 | + /** |
| 231 | + * 计算type的数目 |
| 232 | + */ |
| 233 | + Map<String, Integer> type_count = new HashMap<>(); |
| 234 | + list.stream() |
| 235 | + .filter(x -> JSONObject.fromObject(x).containsKey("type")) |
| 236 | + .map(x -> JSONObject.fromObject(x).getString("type")) |
| 237 | + .forEach(x -> { |
| 238 | + if (type_count.containsKey(x)) type_count.put(x, type_count.get(x) + 1); |
| 239 | + else type_count.put(x, 1); |
| 240 | + }); |
| 241 | + System.out.println(type_count.toString()); |
| 242 | + ##: |
| 243 | + {"type":"收入","money":1000} |
| 244 | + {"type":"支出","money":500} |
| 245 | + {"type":"借贷","money":100} |
| 246 | + 100 |
| 247 | + {借贷=1, 收入=1, 支出=1} |
| 248 | +``` |
0 commit comments