java 8 stream学习整理
Posted 艾白羊
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 8 stream学习整理相关的知识,希望对你有一定的参考价值。
1、什么是stream:
Stream 使用一种类似用 SQL 语句从数据库查询数据的直观方式来提供一种对 Java 集合运算和表达的高阶抽象。
这种风格将要处理的元素集合看作一种流, 流在管道中传输, 并且可以在管道的节点上进行处理, 比如筛选, 排序,聚合等。
元素流在管道中经过中间操作(intermediate operation)的处理,最后由最终操作(terminal operation)得到前面处理的结果。
2、常用的流操作:
2.1、map:map 方法用于映射每个元素到对应的结果。
2.11、List对象转List<Long>
@Slf4j public class Streamdemo { public static List<User> createList() { User user = new User(1L, "by", 18, "音乐"); User user1 = new User(2L, "gz", 26, "音乐"); User user2 = new User(3L, "aby", 19, "旅行"); List<User> userList = Lists.newArrayList(user, user1, user2); return userList; } public static void main(String[] args) { List<User> userList = createList(); // List对象转List<Long> List<Long> longList = userList.stream().map(o->o.getId()).collect(Collectors.toList()); log.info("longList"+longList); } }
2.2、filter:filter 方法用于通过设置的条件过滤出元素。
2.21、集合相减
@Slf4j public class Streamdemo { public static List<User> createList() { User user = new User(1L, "by", 18, "音乐"); User user1 = new User(2L, "gz", 26, "音乐"); User user2 = new User(3L, "aby", 19, "旅行"); List<User> userList = Lists.newArrayList(user, user1, user2); return userList; } public static List<User> newList() { User user = new User(1L, "by", 18, "音乐"); User user1 = new User(2L, "gz", 26, "音乐"); List<User> userList = Lists.newArrayList(user, user1); return userList; } public static void main(String[] args) { List<User> userList = createList(); List<User> newList = newList(); //userList - newList List<User> resultList = createList().stream().filter(o->!newList.contains(o)).collect(Collectors.toList()); log.info("resultList"+resultList); } }
2.3 Collectors : Collectors 类实现了很多归约操作。
2.31、List转Map
@Slf4j public class Streamdemo { public static List<User> createList() { User user = new User(1L, "by", 18, "音乐"); User user1 = new User(2L, "gz", 26, "音乐"); User user2 = new User(3L, "aby", 19, "旅行"); List<User> userList = Lists.newArrayList(user, user1, user2); return userList; } public static void main(String[] args) { List<User> userList = createList(); //key = id , value = userName Map<Long, String> lsMap = userList.stream().collect(Collectors.toMap(User::getId, User::getUserName)); log.info("lsMap" + lsMap); //key = userName , value = love Map<String, String> ssMap = userList.stream().collect(Collectors.toMap(o -> o.getUserName(), o -> o.getLove())); log.info("ssMap" + ssMap); //key = id , value = User Map<Long, User> luMap = userList.stream().collect(Collectors.toMap(o -> o.getId(), o -> o)); log.info("luMap" + luMap); //key = love + userName , value = User Map<String,User> map = new HashMap<>(16); userList.forEach(o->{ map.put(o.getLove()+o.getUserName(),o); }); }
参考:https://lw900925.github.io/java/java8-stream-api.html
以上是关于java 8 stream学习整理的主要内容,如果未能解决你的问题,请参考以下文章