======================================================Collection常見工具類:
import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.stream.Collectors; import org.springframework.util.CollectionUtils; public class CollectionUtil { /** * 集合工具類匯總: * * static void swap(List<?> list, int i, int j) * 在指定List的指定位置i,j處交換元素。 * static void rotate(List<?> list, int distance) * 當distance為正數時,將List集合的后distance個元素“整體”移到前面;當distance為負數時,將list集合的前distance個元素“整體”移到后邊。該方法不會改變集合的長度。 * static Integer max(Collection<? extends Integer> coll) * 輸出最大數 * static Integer min(Collection<? extends Integer> coll) * 輸出最小數 * static boolean Collections.replaceAll(list, oldVal, newVal) * 替換所有元素值oldVal為newVal * static Integer Collections.frequency(list, obj) * 列表中出現指定元素的次數 * * ****** 適用於List<Integer> */ /*** * 對數據進行分組List,每組最多eachGroupSize個 * @param data * @param eachGroupSize * @return */ public static <T> List<List<T>> splitToGroups(Collection<T> data, int eachGroupSize){ if(CollectionUtils.isEmpty(data)){ return new ArrayList<>(0); } if(eachGroupSize <= 0){ throw new IllegalArgumentException("參數錯誤"); } List<List<T>> result = new ArrayList<>(); for(int index=0; index<data.size(); index+=eachGroupSize){ result.add(data.stream().skip(index).limit(eachGroupSize).collect(Collectors.toList())); } return result; } }
======================================================Collection常見工具測試類:
/** * 集合常見操作 */ @Test public void test_collections(){ List<Integer> intList = new ArrayList<>(); intList.add(100); intList.add(89); intList.add(14); intList.add(1); intList.add(50); //輸出最大數 System.out.println(Collections.max(intList)); //輸出最小數 System.out.println(Collections.min(intList)); //輸出原列表 System.out.println(intList); //替換所有元素值oldVal為newVal Collections.replaceAll(intList, 89, 90); System.out.println(intList); //在指定List的指定位置i,j處交換元素 Collections.swap(intList, 2, 1); System.out.println(intList); //對List集合元素進行隨機排序 Collections.shuffle(intList); System.out.println(intList); //當distance為正數時,將List集合的后distance個元素“整體”移到前面;當distance為負數時,將list集合的前distance個元素“整體”移到后邊。該方法不會改變集合的長度 Collections.rotate(intList, 3); System.out.println(intList); //列表中出現指定元素的次數 System.out.println(Collections.frequency(intList, 50)); } /** * 對集合進行分組List */ @Test public void test_splitToGroups(){ List<Integer> intList = new ArrayList<>(); for(int i=4; i>=0; i--){ intList.add(i); } System.out.println(intList); List<List<Integer>> groups = CollectionUtil.splitToGroups(intList, 3); System.out.println(groups); }