目录
流的简单介绍
Java 8 中,引入了流(Stream)的概念,利用提供的Stream API,我们可以方便的操作集合数据,这种方式很类似于使用SQL对数据库的操作。
stream特性
stream只能被“消费”一次,一旦遍历过就会失效,就像容器的迭代器那样,想要再次遍历必须重新生成。
1、Stream 自己不会存储元素。
2、Stream 不会改变源对象。相反,他们会返回一个持有结果的新Stream。
3、Stream 操作是延迟执行的。这意味着他们会等到需要结果的时候才执行。
集合之间互相转换
对象属性转为list
// 把数据放到map ,再转换成list
List<int> ids= userList.stream().map(User::getId).collect(Collectors.toList())
list转map
Map<String,Entity> statMap = userList.stream().collect(Collectors.toMap(User::getId, u -> u));
map的keys、values转list
Map<Integer, String> map = new HashMap<>();
map.put(10, "语文");
map.put(20, "数学");
map.put(30, "体育");
map.put(40, "政治");
map.put(50, "英语");
// key转list
List<Integer> keys= map.keySet().stream().collect(Collectors.toList());
// value转list
List<String> values= map.values().stream().collect(Collectors.toList());
字符串转list
List<Long> userIdList = Arrays.stream(userIds.split(",")).map(Long::parseLong).collect(Collectors.toList());
list根据某个对象属性去重
// 根据name去重
List<User> userList = users.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(
() -> new TreeSet<User>(Comparator.comparing(User::getName))
), ArrayList::new)
);
// 根据name,sex两个属性去重
List<User> userList = users.stream().collect(
Collectors. collectingAndThen(
Collectors.toCollection(
() -> new TreeSet<User>(Comparator.comparing(o -> o.getName() + ";" + o.getSex()))
), ArrayList::new)
);