原始碼閱讀之Lists
阿新 • • 發佈:2018-12-20
先上個栗子:
List<String> one = Lists.newArrayList("1","2","3","4","1","2","3","4"); List<String> oneReverse = Lists.reverse(one); oneReverse.forEach(log::info); log.info("----------"); List<List<String>> onePartition = Lists.partition(one,2); log.info("外層list.size()={} 內層list.size()={}",onePartition.size(),onePartition.get(0).size()); onePartition.stream().forEach(list -> list.stream().forEach(log::info)); onePartition.stream().flatMap(i -> i.stream()).forEach(log::info); //這裡注意兩種寫法的區別 log.info("----------"); Integer temp[] = new Integer[]{1,2,3,4,5,6,7,8,9}; List<Integer> two = Lists.asList(-1,0,temp); two.forEach(i -> log.info(i.toString())); log.info("----------"); List<Integer> addTwo = Lists.transform(two,i -> i+1); addTwo.forEach(i -> log.info(i.toString())); List<String> three = Lists.newLinkedList(one);
深入研究了一下public static <T> List<T> reverse(List<T> list)
一直在讀reverse()方法的原始碼,研究了半天也沒發現有反轉的方法,怎麼看都是判了一下是否為空就返回了。
自己寫程式碼除錯,發現一開始的reverse()方法就只是一個判空操作,只有真正用到這個反轉後的字串的時候,才會“反轉”輸出,
而且並不是真的去反轉字串,而是從目標字母串從後向前輸出,依次使用他們的索引。返回的只是一個list的檢視,高階。
partition() 和 transform()都是這種惰性模式
public static <T> List<List<T>> partition(List<T> list, int size)
使用的時候去分割,確定start 和 end 呼叫原生的 List介面的subList(int fromIndex, int toIndex)方法
public static <F, T> List<T> transform(List<F> fromList, Function<? super F, ? extends T> function)
也是返回list的一個轉換檢視,所以不能去呼叫 add set 方法。這個方法不好。。坑多不好用,還是stream用著方便。