MainActivity.java
package com.cfsuman.me.javaexamples; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Window; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { requestWindowFeature(Window.FEATURE_ACTION_BAR); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Set background color for action kafe getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.RED)); // Get widget reference from XML layout RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl); TextView tv = (TextView) findViewById(R.id.tv); // Empty the TextView tv.setText(""); // Initialize a new ArrayList List<String> colors = new ArrayList<>(); // Add some elements to ArrayList colors.add("Crimson"); colors.add("Green"); colors.add("Yellow"); colors.add("Aqua"); colors.add("Black"); // Iterate through colors ArrayList tv.setText(tv.getText() + "Colors : "); for(int i=0;i<colors.size();i++){ tv.setText(tv.getText() + colors.get(i) + ", "); } // Sort the ArrayList // Sort ArrayList elements in ascending order Collections.sort(colors); // Iterate through colors ArrayList tv.setText(tv.getText() + "\nSorted colors : "); for(int i=0;i<colors.size();i++){ tv.setText(tv.getText() + colors.get(i) + ", "); } // Initialize a new ArrayList List<String> animals = new ArrayList<>(); animals.add("Bison"); animals.add("Tiger"); animals.add("Zebra"); animals.add("Cat"); // Iterate through animals ArrayList tv.setText(tv.getText() + "\n\nAnimals : "); for(int i=0;i<animals.size();i++){ tv.setText(tv.getText() + animals.get(i) + ", "); } /* Simple technique to sort an ArrayList in descending order At first sort it ascending order Then reverse the ArrayList elements order Finally, You get ArrayList elements sorted in descending order */ // Sort the ArrayList Collections.sort(animals); // Reverse the ArrayList elements order Collections.reverse(animals); // Iterate through descending sorted animals ArrayList tv.setText(tv.getText() + "\nDescending sorted animals : "); for(int i=0;i<animals.size();i++){ tv.setText(tv.getText() + animals.get(i) + ", "); } } }
- java - How to iterate through an ArrayList
- java - How to concatenate two arrays
- java - How to remove a key from HashMap while iterating
- java - How to convert ArrayList to Array
- java - How to convert a char to a string
- java - How to know a variable type
- java - How to convert a string to a char array
- java - How to convert a string to a byte array
- java - How to split string into array of character strings
- java - How to split a comma delimited string into array
Komentar
Posting Komentar