当前位置:  首页>> 技术小册>> Java语言基础10-Java中的集合

  • 反转 List 中元素的顺序:
  1. public static void reverse(List<?> list) {}
  • 对 List 集合中的元素进行随机排序:
  1. public static void shuffle(List<?> list) {}
  • 根据元素的自然顺序对 List 集合中的元素进行排序:
  1. public static <T extends Comparable<? super T>> void sort(List<T> list) {}
  • 根据指定的 Comparator 对 List 集合元素进行排序:
  1. public static <T> void sort(List<T> list, Comparator<? super T> c) {}
  • 根据元素的自然顺序,返回给定集合中的最大元素:
  1. public static <T extends Object & Comparable<? super T>> T max(Collection<? extends T> coll) {}
  • 根据指定的 Comparator,返回给定集合中的最大元素:
  1. public static <T> T max(Collection<? extends T> coll, Comparator<? super T> comp) {}
  • 根据元素的自然顺序,返回给定集合中的最小元素:
  1. public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {}
  • 根据指定的 Comparator,返回给定集合中的最小元素:
  1. public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {}
  • 返回指定集合中指定元素出现的次数:
  1. public static int frequency(Collection<?> c, Object o) {}
  • 集合元素的复制:
  1. public static <T> void copy(List<? super T> dest, List<? extends T> src) {}
  • 使用新值替换 List 集合中的所有旧值:
  1. public static <T> boolean replaceAll(List<T> list, T oldVal, T newVal) {}
  • 示例:
  1. package com.github.collections.demo1;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.List;
  5. /**
  6. * @author maxiaoke.com
  7. * @version 1.0
  8. */
  9. public class Test {
  10. public static void main(String[] args) {
  11. List<String> list = new ArrayList<>();
  12. list.add("aa");
  13. list.add("dd");
  14. list.add("hh");
  15. list.add("bb");
  16. System.out.println("list = " + list); // list = [aa, dd, hh, bb]
  17. Collections.reverse(list);
  18. System.out.println("list = " + list); // list = [bb, hh, dd, aa]
  19. String max = Collections.max(list);
  20. System.out.println("max = " + max); // max = hh
  21. int gg = Collections.binarySearch(list, "gg");
  22. System.out.println("gg = " + gg); // gg = -2
  23. }
  24. }

该分类下的相关小册推荐: