public class Test {
public static void main(String[] args) {
// 创建集合
List<Integer> list1 = new ArrayList<Integer>();
list1.add(2);
list1.add(1);
list1.add(4);
list1.add(5);
list1.add(3);
System.out.println(list1);// 结果:[2, 1, 4, 5, 3]
List<Integer> list2 = new ArrayList<Integer>();
list2.add(5);
list2.add(3);
System.out.println(list2);// 结果:[4, 5, 3]
// 1、max(Collection coll) - 根据元素的自然顺序,返回给定 collection 的最大元素
System.out.println(Collections.max(list1));// 结果:5
// 2、max(Collection coll,Comparator c) - 根据指定比较器产生的顺序,返回给定collection 的最大元素
System.out.println(Collections.max(list1, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}));
// 结果:1
// 3、min(Collection coll) - 根据元素的自然顺序,返回给定 collection 的最小元素
System.out.println(Collections.min(list1));// 结果:1
// 4、min(Collection coll,Comparator c) - 根据指定比较器产生的顺序,返回给定collection 的最小元素
System.out.println(Collections.min(list1, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2 - o1;
}
}));
// 结果:5
// 5、frequency(Collection c,Object o) - 返回指定 collection 中等于指定对象的元素数
System.out.println(Collections.frequency(list1, 2));// 结果:1
/*
6、indexOfSubList(List source, List target) - 返回指定源列表中第一次出现指定目标列表的起始位置;
如果没有出现这样的列表,则返回-1
*/
System.out.println(Collections.indexOfSubList(list1, list2));// 结果:3
/*
7、lastIndexOfSubList(List source, List target) - 返回指定源列表中最后一次出现指定目标列表的起始位置;
如果没有出现这样的列表,则返回 -1
*/
System.out.println(Collections.lastIndexOfSubList(list1, list2));//结果:3
// 8、replaceAll(List list, T oldVal, T newVal) - 使用另一个值替换列表中出现的所有某一指定值
Collections.replaceAll(list1, 1, 7);
System.out.println(list1);
// 9、fill(List list, T obj) - 使用指定元素替换指定列表中的所有元素
Collections.fill(list1, 0);
System.out.println(list1);
}
}
java Collections 查找、替换方法
最新推荐文章于 2023-07-21 17:37:53 发布