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));


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM