Java 程式用於整理集合的元素
在本文中,我們來了解如何整理集合的元素。集合是提供架構來儲存和操作物件組的框架。Java 集合可以實現對資料執行的所有操作,例如搜尋、排序、插入、操作和刪除。
以下是同樣的演示 −
假設我們的輸入是 −
Input list: [Java, program, is, fun, and, easy]
理想的輸出是 −
The shuffled list is: [is, easy, program, and, fun, Java]
演算法
Step 1 - START Step 2 - Declare an arraylist namely input_list. Step 3 - Define the values. Step 4 - Using the function shuffle(), we shuffle the elements of the list. Step 5 - Display the result Step 6 - Stop
示例 1
在這裡,我們將所有的操作繫結在一起,並置於“main”函式之下。
import java.util.*;
public class Demo {
public static void main(String[] args){
ArrayList<String> input_list = new ArrayList<String>();
input_list.add("Java");
input_list.add("program");
input_list.add("is");
input_list.add("fun");
input_list.add("and");
input_list.add("easy");
System.out.println("The list is defined as:" + input_list);
Collections.shuffle(input_list, new Random());
System.out.println("The shuffled list is: \n" + input_list);
}
}輸出
The list is defined as:[Java, program, is, fun, and, easy] The shuffled list is: [is, Java, fun, program, easy, and]
示例 2
在這裡,我們將操作封裝到函式中,從而展示面向物件程式設計。
import java.util.*;
public class Demo {
static void shuffle(ArrayList<String> input_list){
Collections.shuffle(input_list, new Random());
System.out.println("The shuffled list is: \n" + input_list);
}
public static void main(String[] args){
ArrayList<String> input_list = new ArrayList<String>();
input_list.add("Java");
input_list.add("program");
input_list.add("is");
input_list.add("fun");
input_list.add("and");
input_list.add("easy");
System.out.println("The list is defined as:" + input_list);
shuffle(input_list);
}
}輸出
The list is defined as:[Java, program, is, fun, and, easy] The shuffled list is: [fun, and, Java, easy, is, program]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP