java筆記:流式編程 數組與List集合互轉


 


 

別再用for循環了。借助org.apache.commons.lang.ArrayUtils更優雅! 

數組轉集合:long[]轉List<Long>

import org.apache.commons.lang.ArrayUtils;

long[] array_long = {1L, 2L, 3L};
//裝箱,把基本類型數組轉成對應的包裝類數組
Long[] array_Long = ArrayUtils.toObject(array_long);
return Arrays.asList(array_Long);

 

集合轉數組:List<Long>轉long[]


import org.apache.commons.lang.ArrayUtils;
long[] array_long = ArrayUtils.toPrimitive(array_Long);



要根據一個List<Entity>,得到entity的id的集合。可以使用流式編程的mapToLong方法;同樣如果得到其他數據類型的集合,可以使用mapToDouble、mapToInt等。

long[] array_long = entList.stream().mapToLong(Enterprise::getEnterpriseId).toArray();

 


要對數組做流式編程,可以先通過Arrays.stream(localEnterpriseIdList)將數組轉換成Stream對象。

 


 

List<Long>轉List<String>

List<Long> l1 = Arrays.asList(1L, 3L, 2L);
List<String> strings = l1.stream().map(String::valueOf).collect(Collectors.toList());

 


 對List<Long>進行排序

import java.util.Collections;
Collections.sort(l2);

 


將List<Long>里的數字轉換成用","分割的字符串 

List<Long> l1 = Arrays.asList(1L, 3L, 2L);
String join = String.join(",", l1.stream().map(String::valueOf).toArray(String[]::new));

 


 

刪除map中符合條件的元素

方法一:loop

Map<String, String> map = Maps.newHashMap();
Iterator<String> iterator = map.keySet().iterator();
while (iterator.hasNext()) {
    String key = iterator.next();
    if (!custFlags.contains(key)) {
        iterator.remove();
    }
}

 

方法二:利用java.util.Collections#removeIf(java8中新增的方法)

Map<String, String> map = Maps.newHashMap();
map.keySet().removeIf(key -> !custFlags.contains(key));

 

 


免責聲明!

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



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