用法示例:
筛选集合中元素大于7的元素
List demoList = new ArrayList<>();
demoList.add(10);
demoList.add(7);
demoList.add(15);
// 筛选集合中元素大于7的元素,返回新的集合
List newList = demoList.stream().filter(item -> item > 7).collect(Collectors.toList());
System.out.println(newList);
// [10, 15]
用法示例:
默认按照从小到大的排序
// 默认按照从小到大排序,返回新的集合
List newList = demoList.stream().sorted().collect(Collectors.toList());
// 默认按照从小到大排序,返回新的集合(和上面效果一样)
List newList2 = demoList.stream().sorted(Comparator.comparingInt(Integer::intValue)).collect(Collectors.toList());
System.out.println(newList);
// [7, 10, 15]
如果要改为从大到小排序,需要加reversed()方法
// 按照从大到小排序,返回新的集合
List newList2 = demoList.stream().sorted(Comparator.comparingInt(Integer::intValue).reversed()).collect(Collectors.toList());
System.out.println(newList2);
// [15, 10, 7]
用法示例:
集合中所有的元素都要满足条件才返回true,否则false。
// 集合中所有元素值都要大于8,才返回true
boolean b1 = demoList.stream().allMatch(item -> item > 8);
System.out.println(b1);
// false
用法示例:
集合中只要有一个元素满足条件就返回true,否则false。
// 只要集合中一个元素值大于12,就返回true
boolean b2 = demoList.stream().anyMatch(item -> item > 12);
System.out.println(b2);
// true
用法示例:
收集集合中所有元素的某个属性值。
List demoList = new ArrayList<>();
Account account = new Account();
account.setId("11");
demoList.add(account);
// 收集集合中所有元素的id属性值,返回新的集合
List newList = demoList.stream().map(Account::getId).collect(Collectors.toList());
System.out.println(newList);
// [11]
把元素中所有id属性拼接为字符串。
String strName = demoList.stream().map(Account::getId).collect(Collectors.joining(","));
// 提供一个集合转字符串逗号拼接方法
List demoList = new ArrayList<>();
demoList.add("1");
demoList.add("2");
demoList.add("3");
String join = StringUtils.join(demoList, ",");
System.out.println(join);
// 1,2,3
用法示例:
遍历集合操作。
demoList.stream().forEach(item->{
System.out.println(item.getId());
});
List demoList = new ArrayList<>();
Account account = new Account();
account.setId("11");
demoList.add(account);
// 集合转map,key为id,value为元素本身。
// 有重复value值取k1(基本上key为主键value本身不会重复)
Map map = demoList.stream().collect(Collectors.toMap(Account::getId, a -> a, (k1, k2) -> k1));
// 根据元素中的属性id对流分组,重复的放在同一个集合里
Map> map = demoList.stream().collect(Collectors.groupingBy(Account::getId));
用法示例:
用于跳过元素。
// 手动分页,跳过(pageNo - 1) * pageSize个元素,截取pageSize个流,返回新的集合。
List = demoList.stream().skip((pageNo - 1) * pageSize).limit(pageSize).collect(Collectors.toList())
留言与评论(共有 0 条评论) “” |