Java Collections rotate()

rotation() 用于将指定列表中的元素旋转指定距离。

1 语法

public static void rotate(List<?> list, int distance)   

2 参数

list:这是将被轮换的列表。

distance:将旋转列表的距离。它可以是零,负数或大于列表的大小。

3 返回值

4 Collections rotate()示例1

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.rotate的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Let us create a list of strings
        List<String>  mylist = new ArrayList<String>();
        mylist.add("Java");
        mylist.add("Python");
        mylist.add("Cobol");
        mylist.add("Perl");
        mylist.add("Android");
        System.out.println("Original List : " + mylist);
        //Rotate the element by distance 3
        Collections.rotate(mylist, 3);
        System.out.println("Rotated List: " + mylist);
    }
}

输出结果为:

Original List : [Java, Python, Cobol, Perl, Android]
Rotated List: [Cobol, Perl, Android, Java, Python]

5 Collections rotate()示例2

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.rotate的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create array list object
        List<Integer> num = new ArrayList<>();
        //Add values in the list
        for (int i = 1; i <= 10; i++) {
            num.add(i);
        }
        System.out.println("Value Before Rotation: "+Arrays.toString(num.toArray()));
        //Rotate the list at distance 5
        Collections.rotate(num, 5);
        System.out.println("Value After Rotation: "+Arrays.toString(num.toArray()));
    }
}

输出结果为:

Value Before Rotation: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Value After Rotation: [6, 7, 8, 9, 10, 1, 2, 3, 4, 5]

6 Collections rotate()示例3

package com.yiidian;

/**
 * 一点教程网: http://www.yiidian.com
 */
/**
 * Java Collections.rotate的例子
 */
import java.util.*;

public class Demo {

    public static void main(String[] args) {
        //Create an array of integers
        Integer arr[] = {10, 20, 30, 40, 50};
        System.out.println("Original Array: "+Arrays.toString(arr));
        //Rotating an array by distance -2
        Collections.rotate(Arrays.asList(arr), -2);
        System.out.println("Modified Array: "+Arrays.toString(arr));
    }
}

输出结果为:

Original Array: [10, 20, 30, 40, 50]
Modified Array: [30, 40, 50, 10, 20]

 

热门文章

优秀文章