import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Comparator; public class My_Collections { public static void print(List list){ list.forEach(s-> System.out.println(s)); } public static void main(String[] args) { List<Integer>integerList=new ArrayList<>(); integerList.add(10); integerList.add(0); integerList.add(3); integerList.add(-1); integerList.add(20); integerList.add(5); //Collections__sort........非自定义排序 Collections.sort(integerList);//从小到大 //print(integerList); //通过Comparable实现自定义排序 Comparator<Integer>comparatorI=new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2-o1;//从大到小 } }; Collections.sort(integerList,comparatorI); //print(integerList); //Collections__shuffle_打乱顺序 Collections.shuffle(integerList); //print(integerList); //Collections__addAll.....添加以元素 Collections.addAll(integerList,4,4,4,4,4); //print(integerList); //Collections__reverse......List集合中的元素进行反转 Collections.reverse(integerList); //print(integerList); //Collections__swap.....指定List集合中的i元素和j元素进行交换 Collections.swap(integerList,4,7); //print(integerList); //Collections__max||min 找最大或者最小值 //System.out.println(Collections.max(integerList)); //System.out.println(Collections.min(integerList)); //Collections__frequency... 该方法可以返回指定元素在指定集合中一共出现的次数 int ans=Collections.frequency(integerList,4); //System.out.println(ans); //Collections__copy.....将指定的旧集合中的元素拷贝到指定的新集合中 //****当新集合的长度小于旧集合时,抛出下标越界异常**** List<Integer>newlist=new ArrayList<>(); for(int i=0;i<integerList.size();i++){ newlist.add(null); } try{ Collections.copy(newlist,integerList); }catch(Exception e){ System.out.print("新集合的长度小于旧集合时不能直接拷贝,否则抛出以下异常:"); System.out.println(e.toString()); } //Collections_replaceAll..... 该方法可以将集合中指定的旧值全部替换为指定的新值 Collections.replaceAll(integerList,4,0); //print(integerList); } }
【记录】Java Collections类方法大全
最新推荐文章于 2024-07-10 21:37:49 发布