Collections.shuffle() से लिस्ट को रैंडमाइज़ करना
यह उदाहरण दर्शाता है कि Android में Collections.shuffle() का उपयोग करके लिस्ट मानों को रैंडम ऑर्डर में कैसे प्रिंट किया जाता है।
चरण 1: नया प्रोजेक्ट बनाएं
Android Studio में File → New Project पर जाएं और प्रोजेक्ट बनाएं।
चरण 2: लेआउट फ़ाइल (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<EditText android:id="@+id/name" android:layout_width="match_parent"
android:hint="नाम दर्ज करें" android:layout_height="wrap_content" />
<LinearLayout android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button android:id="@+id/save" android:text="सेव करें"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
<Button android:id="@+id/refresh" android:text="रिफ्रेश"
android:layout_width="wrap_content" android:layout_height="wrap_content" />
</LinearLayout>
<ListView android:id="@+id/listView" android:layout_width="match_parent"
android:layout_height="wrap_content"></ListView>
</LinearLayout>
चरण 3: MainActivity.java
package com.example.myapp;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
public class MainActivity extends AppCompatActivity {
EditText name;
ArrayAdapter<String> arrayAdapter;
ArrayList<String> arrayList;
Set<String> set = new HashSet<>();
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList = new ArrayList<>();
name = findViewById(R.id.name);
listView = findViewById(R.id.listView);
findViewById(R.id.refresh).setOnClickListener(v -> {
if (arrayAdapter != null) {
arrayAdapter.notifyDataSetChanged();
listView.invalidateViews();
}
});
findViewById(R.id.save).setOnClickListener(v -> {
String input = name.getText().toString().trim();
if (!input.isEmpty()) {
set.add(input);
arrayList.clear();
arrayList.addAll(set);
// लिस्ट को रैंडमली शफल करें
Collections.shuffle(arrayList);
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, arrayList);
listView.setAdapter(arrayAdapter);
Toast.makeText(this, "इन्सर्ट किया गया", Toast.LENGTH_LONG).show();
} else {
name.setError("नाम दर्ज करें");
}
});
}
}
ऐप चलाएं
डिवाइस कनेक्ट करें और ऐप चलाएं।

परिणाम में, हम सेट एलिमेंट्स के नामों को एडाप्टर में रैंडम ऑर्डर में इन्सर्ट कर रहे हैं। Collections.shuffle() एलिमेंट्स को रैंडमली पुनर्व्यवस्थित करता है।