参考: java8新特性 lambda Stream map
1、 数值Stream的构建
// 数组
IntStream stream1 = IntStream.of(new int[]{1, 2, 3});
// [1,3)
IntStream stream2 = IntStream.range(1, 3);
// [1,3]
IntStream stream3 = IntStream.rangeClosed(1, 3);
// Stream转换为其他类型
Stream<String> stream = Stream.of("hello","world","tom");
// 1. 转换为Array
String[] strArray = stream.toArray(String[]::new);
// 2. 转换为Collection
List<String> list1 = stream.collect(Collectors.toList());
List<String> list2 = stream.collect(Collectors.toCollection(ArrayList::new));
Set<String> set3 = stream.collect(Collectors.toSet());
Set<String> set4 = stream.collect(Collectors.toCollection(HashSet::new));
// 3. 转换为String
String str = stream.collect(Collectors.joining()).toString();
2、 list数据转换(遍历、转换为map)
// List 转化为map 1: 直接toMap
List<String> list = Arrays.asList("one", "two", "three", "four");
Map<String, String> map1 = list.stream().collect(Collectors.toMap(
string -> string.substring(0,1),
string -> string));
// List 转化为map 2: 新建一个空的map,遍历list逐个插入
Map<String,String> map2 = new HashMap<>(10);
list.forEach(string -> {
map2.put(string.substring(0,1),string);
});
// list遍历进行数据转换
list.forEach(s -> s.substring(1));
List<String> stringList = list.stream().map(String::toUpperCase).collect(Collectors.toList());
List<Integer> integerList = list.stream().map(s -> {
int length = s.length();
return length * length;
}).collect(Collectors.toList());
// java8 sorted filter
list.stream().sorted().filter(s->s.startsWith("j")).forEach(System.out::println);
// 按照字符串的长短排序
list.stream().sorted((s1,s2)->s1.length()-s2.length()).forEach(System.out::println);
3、 map数据转换(转换为list、sorted排序)
// Java 7, Convert all Map keys to a List
Map<String, String> map = new HashMap<>();
List<String> result = new ArrayList(map.keySet());
// Java 8, Convert all Map keys to a List
List<String> result2 = map.keySet().stream()
.collect(Collectors.toList());
// Java 8, 过滤并转换为想要的list,满足filter中的条件需要保留
List<String> result3 = map.values().stream()
.filter(x -> !"apple".equalsIgnoreCase(x))
.collect(Collectors.toList());