Java8新特性stream流
一、包装数据类型
代码语言:javascript
复制@Test
public void main22() {
List<Integer> list = new ArrayList<Integer>(){{
add(7); add(5); add(1); add(2);
add(8); add(4); add(3); add(6);
add(3); add(6); add(3); add(6);
}};
// 过滤
List<Integer> filterList = list.stream().filter(a -> a < 5).collect(Collectors.toList());
// 排序(正序)
List<Integer> sortList1 = list.stream().sorted().collect(Collectors.toList());
List<Integer> sortList2 = list.stream().sorted(Comparator.comparing(a -> a, Comparator.naturalOrder())).collect(Collectors.toList());
// 排序(倒序)
List<Integer> sortList3 = list.stream().sorted(Comparator.comparing(a -> a, Comparator.reverseOrder())).collect(Collectors.toList());
// 最大数
Integer max = list.stream().max(Comparator.comparing(a -> a, Comparator.naturalOrder())).get();
// 最小数
Integer min = list.stream().min(Comparator.comparing(a -> a, Comparator.naturalOrder())).get();
// 去重
List<Integer> distinctList = list.stream().distinct().collect(Collectors.toList());
// 对每个元素进行操作
List<Integer> mapList = list.stream().map(a -> a * a).collect(Collectors.toList());
System.out.println(max);
System.out.println(min);
mapList.forEach(a -> System.out.print(a " "));
}
二、Map类型
代码语言:javascript
复制import org.apache.commons.lang.StringUtils;
@Test
public void test() {
HashMap<String, Integer> map = new HashMap<String, Integer>(){{
put("A", 1); put("B", 2); put("C", 3); put("D", 4);
put("E", 1); put("F", 1); put("", 1); put("", 1);
}};
// key集合转list
List<String> keyList1 = map.keySet().stream().filter(a -> StringUtils.isNotBlank(a)).collect(Collectors.toList());
List<String> keyList2 = map.entrySet().stream().map(entry -> entry.getKey()).filter(a -> StringUtils.isNotBlank(a)).collect(Collectors.toList());
// value集合转list
List<Integer> valueList = map.entrySet().stream().map(entry -> entry.getValue()).collect(Collectors.toList());
// 处理value,同理可处理key
Map<String, Integer> newMap = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, a -> a.getValue() * a.getValue()));
// key value换位,key冲突时,新value替换旧value
Map<Integer, String> reMap1 = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue,
Map.Entry::getKey,
(String val1, String val2) -> val2
));
// key value换位,key冲突时,加入value列表中
Map<Integer, List<String>> reMap2 = map.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue,
a -> new ArrayList<String>(){{ add(a.getKey()); }},
(List<String> v1, List<String> v2) -> {
v1.addAll(v2);
return v1;
}
));
keyList2.forEach(a -> System.out.printf(a " "));
System.out.println();
reMap2.entrySet().forEach(entry -> System.out.println("key: " entry.getKey() ", val: " entry.getValue()));
}
三、对象List
代码语言:javascript
复制@Test
public void test() {
List<User> list = new ArrayList<User>() {{
add(new User(1, "半月", 18));
add(new User(2, "无霜", 22));
add(new User(3, "半月无霜", 24));
add(new User(3, "半霜", 28));
add(new User(4, "半霜", 28));
}};
// 转Map<id, user>,如遇到key冲突,可参考第二段map解决办法
Map<Integer, User> map1 = list.stream().collect(Collectors.toMap(User::getId, Function.identity()));
Map<Integer, User> map2 = list.stream().collect(Collectors.toMap(User::getId, a -> a));
// 查找
User user = list.stream().filter(a -> "半月".equals(a.getName())).findFirst().get();
// 过滤计数
long count = list.stream().filter(a -> a.getAge() >= 22).count();
// 排序(通过年龄排正序)
List<User> orderList = list.stream().sorted(Comparator.comparing(User::getAge, Comparator.naturalOrder())).collect(Collectors.toList());
// 排序(通过年龄排倒序)
List<User> reorderList = list.stream().sorted(Comparator.comparing(User::getAge, Comparator.reverseOrder())).collect(Collectors.toList());
// 对象去重(通过ID去重)
List<User> unionUser = list.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(o -> o.getId()))), ArrayList::new));
// 属性集合(此处为名字集合)
List<String> nameList = list.stream().map(User::getName).collect(Collectors.toList());
// 截取,skip:跳过前n个,limit:取n个
List<User> limitList = list.stream().skip(1).limit(2).collect(Collectors.toList());
// 判断是否存在(半月是否存在)
boolean isHave1 = list.stream().anyMatch(a -> "半月".equals(a.getName()));
// 判断所有是否满足(是否都大于16岁)
boolean fullAge = list.stream().allMatch(a -> a.getAge() > 16);
// 判断是否不存在(里面没有ID为10的用户)
boolean isHave2 = list.stream().noneMatch(a -> "10".equals(a.getId()));
limitList.forEach(System.out::println);
System.out.println(isHave2? "没有ID为10的用户": "有ID为10的用户");
}
@Data
@AllArgsConstructor
class User{
private Integer id;
private String name;
private Integer age;
}
四、分组
代码语言:javascript
复制@Test
public void test() throws InterruptedException {
List<User> list = new ArrayList<User>() {{
add(new User("半月1", 18, 90));
add(new User("半月2", 18, 80));
add(new User("半月3", 18, 70));
add(new User("半月4", 18, 60));
add(new User("半月无霜1", 20, 90));
add(new User("半月无霜2", 20, 80));
add(new User("半月无霜3", 20, 70));
add(new User("半月无霜4", 20, 60));
}};
// 分组,通过分数对用户进行分组
Map<Integer, List<User>> groupByScore = list.stream().collect(Collectors.groupingBy(
User::getScore,
Collectors.mapping(Function.identity(), Collectors.toList())
));
// 分组计算,通过年龄分组计算最大的分数值
Map<Integer, Optional<Integer>> maxScoreByAge = list.stream().collect(Collectors.groupingBy(
User::getAge,
Collectors.mapping(User::getScore, Collectors.maxBy(Integer::compareTo))
));
// 按照条件分组,及格和不及格的两批人的最高分
Map<Boolean, Optional<Integer>> maxScoreByPassMark = list.stream().collect(Collectors.partitioningBy(
user -> user.getScore() >= 60,
Collectors.mapping(User::getScore, Collectors.maxBy(Integer::compareTo))
));
maxScoreByPassMark.keySet().forEach(a -> System.out.println("是否及格:" a ":" maxScoreByPassMark.get(a)));
}
@Data
@AllArgsConstructor
class User{
private String name;
private Integer age;
private Integer score;
}