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”函数之下。

Open Compiler
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); } }

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

输出

The list is defined as:[Java, program, is, fun, and, easy]
The shuffled list is:
[is, Java, fun, program, easy, and]

示例 2

在这里,我们将操作封装到函数中,从而展示面向对象编程。

Open Compiler
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]

更新于: 30-3 月-2022

215 的观点

开启您的 事业

完成课程以获得认证

开始
广告