Java的Collections工具类

Java的Collections工具类位于java.util包中,提供了一系列静态方法用于操作集合(ListSetMap等)。以下是Collections类中一些常用方法的列表和使用实例:

常用方法列表

  1. sort(List<T> list):对列表进行升序排序。
  2. sort(List<T> list, Comparator<? super T> c):根据指定的比较器对列表进行排序。
  3. reverse(List<?> list):反转列表中元素的顺序。
  4. shuffle(List<?> list):随机打乱列表中元素的顺序。
  5. copy(List<? super T> dest, List<? extends T> src):将所有元素从一个列表复制到另一个列表。
  6. fill(List<? super T> list, T obj):用指定的元素替换列表中的所有元素。
  7. replaceAll(List<T> list, T oldVal, T newVal):替换列表中所有出现的指定元素。
  8. min( Collection<? extends T> coll, Comparator<? super T> comp):返回集合中的最小元素。
  9. max( Collection<? extends T> coll, Comparator<? super T> comp):返回集合中的最大元素。
  10. emptyIterator():返回一个空的迭代器。
  11. singleton(T o):返回一个只包含一个元素的不可变的集合。
  12. singletonList(T o):返回一个只包含一个元素的不可变的列表。
  13. unmodifiableCollection(Collection<? extends T> c):返回一个不可修改的集合视图。
  14. frequency(Collection<?> c, Object o):返回指定元素在集合中出现的次数。

使用实例

排序列表

List<Integer> numbers = Arrays.asList(4, 2, 5, 1, 3); Collections.sort(numbers); // 使用自然顺序排序 System.out.println(numbers); // 输出:[1, 2, 3, 4, 5] Comparator<Integer> comparator = new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { return o2.compareTo(o1); // 降序排序 } }; Collections.sort(numbers, comparator); System.out.println(numbers); // 输出:[5, 4, 3, 2, 1]

反转列表

List<String> fruits = Arrays.asList("apple", "banana", "cherry"); Collections.reverse(fruits); System.out.println(fruits); // 输出:[cherry, banana, apple]

随机打乱列表

List<String> animals = Arrays.asList("dog", "cat", "elephant", "rabbit"); Collections.shuffle(animals); System.out.println(animals); // 输出顺序随机的列表,如:[cat, rabbit, elephant, dog]

复制列表

List<String> originalList = Arrays.asList("sun", "moon", "star"); List<String> copyList = new ArrayList<>(); Collections.copy(copyList, originalList); System.out.println(copyList); // 输出:[sun, moon, star]

替换列表中的元素

List<String> words = Arrays.asList("hello", "world", "java"); Collections.replaceAll(words, "java", "javafx"); System.out.println(words); // 输出:[hello, world, javafx]

获取集合中元素的频率

List<String> items = Arrays.asList("apple", "banana", "apple", "cherry", "banana", "apple"); int frequency = Collections.frequency(items, "apple"); System.out.println(frequency); // 输出:3

创建不可修改的集合视图

List<String> original = new ArrayList<>(Arrays.asList("one", "two", "three")); List<String> unmodifiable = Collections.unmodifiableList(original); // 下面的代码会抛出UnsupportedOperationException,因为尝试修改不可修改的集合 // unmodifiable.add("four");

Collections工具类提供的方法使得集合的操作更加方便和高效。在实际开发中,应根据具体需求选择合适的方法来操作集合。

posted @ 2024-03-28 13:34  一只小松许  阅读(4)  评论(0编辑  收藏  举报