Collections class set operation Explanation

Collections is a class operation Set Java offers, List and Map and other tools collection. Collections class provides a set of operations of a number of static methods, static methods to sort the collection by means of these elements can be achieved, search and replace and copy operations.

Sort (forward and reverse)

Collections provides a method for sorting List collection element.

	void reverse(List list):对指定 List 集合元素进行逆向排序。
	
	void shuffle(List list):对 List 集合元素进行随机排序(shuffle 方法模拟了“洗牌”动作)。
	
	void sort(List list):根据元素的自然顺序对指定 List 集合的元素按升序进行排序。
	
	void sort(List list, Comparator c):根据指定 Comparator 产生的顺序对 List 集合元素进行排序。
	
	void swap(List list, int i, int j):将指定 List 集合中的 i 处元素和 j 处元素进行交换。
	
	void rotate(List list, int distance):当 distance 为正数时,将 list 集合的后 distance 个元素“整体”移到前面;当 distance 为负数时,将 list 集合的前 distance 个元素“整体”移到后面。该方法不会改变集合的长度。

After the user enters the output of five commodity price sort. Collections class required here sort () method to sort the order from low to high on its last output the sorted results.

code show as below:

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        List prices = new ArrayList();
        for (int i = 0; i < 5; i++) {
            System.out.println("请输入第 " + (i + 1) + " 个商品的价格:");
            int p = input.nextInt();
            prices.add(Integer.valueOf(p)); // 将录入的价格保存到List集合中
        }
        Collections.sort(prices); // 调用sort()方法对集合进行排序
        System.out.println("价格从低到高的排列为:");
        for (int i = 0; i < prices.size(); i++) {
            System.out.print(prices.get(i) + "\t");
        }
    }
}

As the above code, entry 5 circulation price, and the price of each of the stored set of prices has been defined in the List, and then use the sort Collections class () method of the set of elements in ascending order. Finally, the use for the collection loop through the users, an output element of the set.

该程序的执行结果如下所示。 
请输入第 1 个商品的价格:
98
请输入第 2 个商品的价格:
48
请输入第 3 个商品的价格:
66
请输入第 4 个商品的价格:
80
请输入第 5 个商品的价格:
18
价格从低到高的排列为:
18    48    66    80    98

Using reverse Collections class () method to save the set of List 5 is inverted to sort tradename, product information and outputs the sorted. code show as below:

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        List students = new ArrayList();
        System.out.println("******** 商品信息 ********");
        for (int i = 0; i < 5; i++) {
            System.out.println("请输入第 " + (i + 1) + " 个商品的名称:");
            String name = input.next();
            students.add(name); // 将录入的商品名称存到List集合中
        }
        Collections.reverse(students); // 调用reverse()方法对集合元素进行反转排序
        System.out.println("按录入时间的先后顺序进行降序排列为:");
        for (int i = 0; i < 5; i++) {
            System.out.print(students.get(i) + "\t");
        }
    }
}

As the above code, the first input loop 5 commodity name, and saves the name of the List collection, and then call the Collections class reverse () method of the ordered set of elements is reversed. Finally, using the elements of the output set will be sorted for recycling.

Executing the program, the output results are shown below.

******** 商品信息 ********
请输入第 1 个商品的名称:
果粒橙
请输入第 2 个商品的名称:
冰红茶
请输入第 3 个商品的名称:
矿泉水
请输入第 4 个商品的名称:
软面包
请输入第 5 个商品的名称:
巧克力
按录入时间的先后顺序进行降序排列为:
巧克力    软面包    矿泉水    冰红茶    果粒橙   

Find and replace operations

Collections provides the following commonly used to find, alternative methods set of elements.

	int binarySearch(List list, Object key):使用二分搜索法搜索指定的 List 集合,以获得指定对象在 List 集合中的索引。如果要使该方法可以正常工作,则必须保证 List 中的元素已经处于有序状态。
	
	Object max(Collection coll):根据元素的自然顺序,返回给定集合中的最大元素。
	
	Object max(Collection coll, Comparator comp):根据 Comparator 指定的顺序,返回给定集合中的最大元素。
	
	Object min(Collection coll):根据元素的自然顺序,返回给定集合中的最小元素。
	
	Object min(Collection coll, Comparator comp):根据 Comparator 指定的顺序,返回给定集合中的最小元素。
	
	void fill(List list, Object obj):使用指定元素 obj 替换指定 List 集合中的所有元素。
	
	int frequency(Collection c, Object o):返回指定集合中指定元素的出现次数。
	
	int indexOfSubList(List source, List target):返回子 List 对象在父 List 对象中第一次出现的位置索引;如果父 List 中没有出现这样的子 List,则返回 -1。
	
	int lastIndexOfSubList(List source, List target):返回子 List 对象在父 List 对象中最后一次出现的位置索引;如果父 List 中没有岀现这样的子 List,则返回 -1。
	
	boolean replaceAll(List list, Object oldVal, Object newVal):使用一个新值 newVal 替换 List 对象的所有旧值 oldVal。

It requires users to enter three trade names, and then use the Collections class fill () method of product information reset operation, so all names are changed to "Missing." code show as below:

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        List products = new ArrayList();
        System.out.println("******** 商品信息 ********");
        for (int i = 0; i < 3; i++) {
            System.out.println("请输入第 " + (i + 1) + " 个商品的名称:");
            String name = input.next();
            products.add(name); // 将用户录入的商品名称保存到List集合中
        }
        System.out.println("重置商品信息,将所有名称都更改为'未填写'");
        Collections.fill(products, "未填写");
        System.out.println("重置后的商品信息为:");
        for (int i = 0; i < products.size(); i++) {
            System.out.print(products.get(i) + "\t");
        }
    }
}

As the above code, the first three input cycles trade name, product information and stores them into the set of List, then call fill Collections class () method of the values ​​of all elements in the set is replaced with "Missing." Finally, using the elements of the output set will be replaced for loop.

Run the program execution results are shown below.

******** 商品信息 ********
请输入第 1 个商品的名称:
苏打水
请输入第 2 个商品的名称:
矿泉水
请输入第 3 个商品的名称:
冰红茶
重置商品信息,将所有名称都更改为'未填写'
重置后的商品信息为:
未填写    未填写    未填写    

4 stored in a data set, the maximum and minimum number of elements and specifying the data appears in the set outputs.

public class Test {
    public static void main(String[] args) {
        ArrayList nums = new ArrayList();
        nums.add(2);
        nums.add(-5);
        nums.add(3);
        nums.add(0);
        System.out.println(nums); // 输出:[2, -5, 3, 0]
        System.out.println(Collections.max(nums)); // 输出最大元素,将输出 3
        System.out.println(Collections.min(nums)); // 输出最小元素,将输出-5
        Collections.replaceAll(nums, 0, 1);// 将 nums中的 0 使用 1 来代替
        System.out.println(nums); // 输出:[2, -5, 3, 1]
        // 判断-5在List集合中出现的次数,返回1
        System.out.println(Collections.frequency(nums, -5));
        Collections.sort(nums); // 对 nums集合排序
        System.out.println(nums); // 输出:[-5, 1, 2, 3]
        // 只有排序后的List集合才可用二分法查询,输出3
        System.out.println(Collections.binarySearch(nums, 3));
    }
}

As the above code is added to List set of four data, and then call the Collections class max () and min () method to output the set maximum and minimum elements, the replaceAll () Replace element, Frequency () whether the specified data set in List the number that appears, finally dichotomy queries binarySearch ().

Run the above procedures, the results of the following:

[2, -5, 3, 0]
3
-5
[2, -5, 3, 1]
1
[-5, 1, 2, 3]
3

copy

copy Collections class () static method used to copy all of the specified elements in the collection to another collection. After performing copy () method, the target set for each copied element index set equal to the index of the source element.

Syntax copy () method is as follows:

void copy(List <? super T> dest,List<? extends T> src)

Wherein, dest denotes a set of target objects, src denotes a source collection object.

note: Length of the target set and a length of at least the same set of sources, the target set if a longer length, the remaining elements of the target set not affected. If the target set is not long enough and can not contain the entire source collection element, the program will throw an IndexOutOfBoundsException.

Five trade names stored in a collection, now replace the 3 wherein the use of the Collections class copy () method. code show as below:

public class Test {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        List srcList = new ArrayList();
        List destList = new ArrayList();
        destList.add("苏打水");
        destList.add("木糖醇");
        destList.add("方便面");
        destList.add("火腿肠");
        destList.add("冰红茶");
        System.out.println("原有商品如下:");
        for (int i = 0; i < destList.size(); i++) {
            System.out.println(destList.get(i));
        }
        System.out.println("输入替换的商品名称:");
        for (int i = 0; i < 3; i++) {
            System.out.println("第 " + (i + 1) + " 个商品:");
            String name = input.next();
            srcList.add(name);
        }
        // 调用copy()方法将当前商品信息复制到原有商品信息集合中
        Collections.copy(destList, srcList);
        System.out.println("当前商品有:");
        for (int i = 0; i < destList.size(); i++) {
            System.out.print(destList.get(i) + "\t");
        }
    }
}

As the above code, the first two List object creates and destList srcList, and adding a set of five elements destList added srcList three elements to set, and then call the Collections class copy () method set srcList all the elements copied to destList collection. Since destList set contains five elements, the last two elements are not so covered.

Running the program, the specific implementation results are shown below.

原有商品如下:
苏打水
木糖醇
方便面
火腿肠
冰红茶
输入替换的商品名称:
第 1 个商品:
燕麦片
第 2 个商品:
八宝粥
第 3 个商品:
软面包
当前商品有:
燕麦片    八宝粥    软面包    火腿肠    冰红茶
Published 457 original articles · won praise 94 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_45743799/article/details/104715657