Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để trộn các phần tử của một tập hợp

Trong bài viết này, chúng ta sẽ hiểu cách xáo trộn các phần tử của một tập hợp. Bộ sưu tập là một khung cung cấp kiến ​​trúc để lưu trữ và thao tác với nhóm các đối tượng. JavaCollections có thể đạt được tất cả các thao tác mà bạn thực hiện trên dữ liệu như tìm kiếm, sắp xếp, chèn, thao tác và xóa.

Dưới đây là một minh chứng về điều tương tự -

Giả sử đầu vào của chúng tôi là -

Input list: [Java, program, is, fun, and, easy]

Đầu ra mong muốn sẽ là -

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

Thuật toán

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

Ví dụ 1

Ở đây, chúng tôi liên kết tất cả các hoạt động với nhau trong hàm "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);
   }
}

Đầu ra

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

Ví dụ 2

Ở đây, chúng tôi đóng gói các hoạt động thành các hàm trưng bày lập trình hướng đối tượng.

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

Đầu ra

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