publicdoubleapply(double x, double y){ switch (this) { case PLUS: return x + y; case MINUS: return x - y; case TIMES: return x * y; case DIVIDE: return x / y; } thrownew AssertionError("Unknown op: " + this); } }
Predicate<String> checkLength = val -> val.length() > 5; Predicate<String> startWith = val -> val.startsWith("B"); List<String> ret = Stream.of("Apple", "Banana", "BBC").filter(checkLength.and(startWith)).collect(Collectors.toList()); System.out.println("-------------- Test AND result--------------"); ret.forEach(System.out::println);
ret = Stream.of("Apple", "Banana", "BBC").filter(checkLength.or(startWith)).collect(Collectors.toList()); System.out.println("-------------- Test OR result--------------"); ret.forEach(System.out::println);
ret = Stream.of("Apple", "Banana", "BBC").filter(checkLength.negate()).collect(Collectors.toList()); System.out.println("-------------- Test NEGATE result--------------"); ret.forEach(System.out::println);
ret = Stream.of("Apple", "Banana", "BBC").filter(Predicate.not(checkLength)).collect(Collectors.toList()); System.out.println("-------------- Test NOT result--------------"); ret.forEach(System.out::println);
System.out.println("-------------- Test EQUALS result--------------"); System.out.println(Predicate.isEqual("abc").test("abc"));
// output: -------------- Test AND result-------------- Banana -------------- Test OR result-------------- Banana BBC -------------- Test NEGATE result-------------- Apple BBC -------------- Test NOT result-------------- Apple BBC -------------- Test EQUALS result-------------- true
Function
接受参数,计算并返回所得的值
1 2 3 4 5
// 接收一个字符串并将其转化成 integer 类型 Function<String, Integer> func = Integer::valueOf; int ret = func.apply("100"); System.out.println(ret); // output: 100
同样,他也有变种,而且特别多
name
作用
BiFunction
接收两个参数, 返回值类型自定
DoubleFunction
接收 Double 参数,返回值自定
IntFunction
接收 Int 参数,返回值自定
LongFunction
接收 Long 参数,返回值自定
DoubleToIntFunction
接收 Double 返回 Int
DoubleToLongFunction
接收 Double 返回 Long
IntToDoubleFunction
接收 Int 返回 Double
IntToLongFunction
接收 Int 返回 Long
LongToDoubleFunction
接收 Long 返回 Double
LongToIntFunction
接收 Long 返回 Int
ToDoubleFunction
接收参数类型自定,返回 Double
ToIntFunction
接收参数类型自定,返回 Int
ToLongFunction
接收参数类型自定,返回 Long
ToIntBiFunction
接收两个参数, 返回 Int
ToLongBiFunction
接收两个参数, 返回 Long
ToDoubleBiFunction
接收两个参数, 返回 Double
相比其他的几个 *Function 接口, BiFunction 和 Function 要更特殊一点,他们除了最基本的 apply() 之外还有一些额外的方法。
Function 和 BiFunction 还有一个相同的 andThen() 方法,他会再前一个返回值的基础上再做计算
1 2 3 4 5 6 7 8
// 对 Stream 中的数进行 x 100 -10 操作 Function<Integer, Integer> funcx100 = val -> val * 100; Function<Integer, Integer> funcMinus10 = val -> val - 10; List<Integer> ret = Stream.of(1, 2).map(funcx100.andThen(funcMinus10)).collect(Collectors.toList()); ret.forEach(System.out::println); // output: // 90 // 190
初此之外 Function 还有几个特殊的方法, compose() 他是在 apply() 之前执行的,注意泛型返回值的承接
1 2 3 4 5 6
// 设计两个 lambda 函数,将测试字符串中的数字部分抽出来,并格式化 Function<String, Integer> funcComp = val -> {String intVal = val.split(":")[1]; return Integer.valueOf(intVal);}; Function<Integer, String> func = val -> "[" + val + "]"; List<String> ret = Stream.of("Jack:30", "Jerry:18").map(func.compose(funcComp)).collect(Collectors.toList()); ret.forEach(System.out::println);
Function 还有一个 identity() 方法,传入什么返回什么,完全不能领会它有什么用,到是网上一些例子中,可以用来快速生成 map 的用法让人挺印象深刻的
public Map<Boolean, List<Artist>> bandsAndSolo(Stream<Artist> artists) { return artist.collect(partitioningBy(artist -> artist.isSolo())); // artist -> artist.isSolo() 可替换为 Artist::isSolo }
字符串流操作示例:
1
String ret = artists.steam().map(Artist::getName).collect(Collectors.joining(",", "[", "]"));
查询并加入 map 的简化操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// before public Artist getArtist(String name){ Artist artist = artistCache.get(name); if (artist == null) { artist = readArtistFromDB(name); artistCache.put(name, artist); } return artist; }
// after public Artist getArtist(String name){ return artistCache.computeIfAbsent(name, this::readArtistFromDB); }
通过 forEach 简化 map 的统计操作:
1 2 3 4 5 6 7 8 9 10 11 12
// before Map<Artist, Integer> countOfAlbums = new HashMap<>(); for(Map.Entry<Artist, List<Album>> entry : albumsByArtist.entrySet()) { Artist artist = entry.getKey(); List<Album> albums = entry.getValue(); countOfAlbums.put(artist, albums.size()); } // after Map<Artist, Integer> countOfAlbums = new HashMap<>(); albumsByArtist.forEach((artist, albums) -> { countOfAlbums.put(artist, albums.size()); });
This page contains the following errors: error on line 3463 at column 23: Input is not proper UTF-8, indicate encoding ! Bytes: 0x08 0x20 0xE5 0x88 Below is a rendering of the page up to the first error.
Generate random int list, or just a requirement of loop N times
it’s a common requirement and some guys achieve this goal by using Numpy lib, but it’s too heavy. you can do in this way:
1 2 3 4 5 6
import random
for _ in range(10) print(random.randint(0, 100)) # the _ is from 0 - 9
Get index and val at the same time
1 2 3 4 5 6 7 8 9 10
a = ['a','b','c','d'] for idx, val in enumerate(a): print(f'idx = {idx}, val = {val}')
# Output: # idx = 0, val = a # idx = 1, val = b # idx = 2, val = c # idx = 3, val = d
if you want to specify the start index, you can add a second parameter to enumerate func
1 2 3 4 5 6 7 8 9 10 11
# in this case, idx would start from 3 a = ['a','b','c','d'] for idx, val in enumerate(a, 3): print(f'idx = {idx}, val = {val}') # Output: # idx = 3, val = a # idx = 4, val = b # idx = 5, val = c # idx = 6, val = d
Ipython 交互界面重新引入修改后的包
1 2
import importlib importlib.reload(some_module)
for loop one line mode
1 2 3 4 5
user_ids = [record['login'] for record in resp]
# if you need if condition list = [1,2,3,4,5,6] filter = [str(sub + "tt") for sub in list if sub >= 3]