list转map,set,使用stream进行转化

list转map,set,使用stream进行转化


函数式编程:

场景:

从数据库中取出来的数据,经常是list集合类型,但是list转map这种场景虽然不常见,但是有时候也会遇到,最常见的还是转为set进行数据去重。

eg:

1 list转set

 List<Notification> notifications = notificationMapper.selectByExampleWithRowbounds(example,new RowBounds(offset, size));

数据获取到的是list集合,调用参数列表忽略,如果想使用,只需要知道返回的是list。
一般返回的list都是有泛型约束的,所以如果转set集合代码如下:

Set<Long> disUserIds = notifications.stream().map(notify -> notify.getNotifier()).collect(Collectors.toSet());

代码解析:
	以下是stream下的map的源码:

  /**
     * Returns a stream consisting of the results of applying the given
     * function to the elements of this stream.
     *
     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
     * operation</a>.
     *
     * @param <R> The element type of the new stream
     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
     *               <a href="package-summary.html#Statelessness">stateless</a>
     *               function to apply to each element
     * @return the new stream
     */
    <R> Stream<R> map(Function<? super T, ? extends R> mapper);
以上的是接口类,实现类的源码:

		@Override
    @SuppressWarnings("unchecked")
    public final <R> Stream<R> map(Function<? super P_OUT, ? extends R> mapper) {
        Objects.requireNonNull(mapper);
        return new StatelessOp<P_OUT, R>(this, StreamShape.REFERENCE,
                                     StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
            @Override
            Sink<P_OUT> opWrapSink(int flags, Sink<R> sink) {
                return new Sink.ChainedReference<P_OUT, R>(sink) {
                    @Override
                    public void accept(P_OUT u) {
                        downstream.accept(mapper.apply(u));
                    }
                };
            }
        };
    }
	
看都不懂系列。。。。
但是如果想使用的话:照葫芦画瓢,等用熟悉了后在来看源码。

简述代码功能:
	notifications.stream().map(notify -> notify.getNotifier()).collect(Collectors.toSet());
	面向函数式编程: notify是参数,就相当于你自己写的方法, 什么public void getName(param 1,param2)中的paramx,默认的定义类型是泛型约束的类型,后面的.collect是转换为set类型。

2 list转map

  List<User> users = userMapper.selectByExample(userExample);
	获取所有的用户
//转化成map
    Map<Long, User> userMap = users.stream().collect(Collectors.toMap(u -> u.getId(), u -> u));
	
	Collectors.toMap参数是两个,key和value,所以返回的map为u.getId的类型Long,u的类型User

总结

  1. list转set:

    Set<Long> disUserIds = notifications.stream().map(notify -> notify.getNotifier()).collect(Collectors.toSet());

  2. list转map
    List users = userMapper.selectByExample(userExample);
    //转化成map
    Map<Long, User> userMap = users.stream().collect(Collectors.toMap(u -> u.getId(), u -> u));

博客网站 https://yamon.top 个人网站 https://yamon.top/resume GitHub网站 https://github.com/yamonc 欢迎前来访问
原文地址:https://www.cnblogs.com/chenyameng/p/12340758.html