Converting ArrayList to Array :
List fruitList = new ArrayList();
fruitList.add(“Mango”);
fruitList.add(“Banana”);
String[] item = fruitList.toArray(new String[fruitList.size()]);
Converting Array to ArrayList :
// Item is a String Array
List l2 = new ArrayList();
l2 = Arrays.asList(item);
Making ArrayList Readonly ListunmodifiableList= Collections.unmodifiableList(fruitList);
Reversing ArrayList :
Collections.reverse(fruitList);
// It reverses fruitList and when fruitList is printed, it has the reverse order.
Synchronizing ArrayList :
fruitList = Collections.synchronizedList(fruitList);
// we must use synchronize block to avoid non-deterministic behavior
synchronized (fruitList) {
Iterator itr = fruitList.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
Sorting ArrayList in Descending Order:
If the arraylist has the Student objects and if we were to sort the student object based on the name , how can we do this ?
It can be done by using Compartor
Collections.sort(studentList,
new Comparator<Student>()
{
public int compare(Student s1, Student s2)
{
return s2.name().compareTo(s1.name());
}
});
Sort an Array :
String[] fruits = new String[] {“Pineapple”,”Apple”, “Orange”, “Banana”};
Arrays.sort(fruits);
Output :Apple,Banana,Orange,PineApple
Sort an ArrayList:
List fruits = new ArrayList();
fruits.add(“Pineapple”);
fruits.add(“Apple”);
Collections.sort(fruits);
Number of occurrences of String in string of arrays:
String[] array = {“name1″,”name1″,”name2″,”name2”, “name2”};
List sampleList=(List) Arrays.asList(array);
for(String inpt:array){
int frequency=Collections.frequency(sampleList,inpt);
System.out.println(inpt+” “+frequency);
}
Identify Duplicate Strings in Array of Strings:
All you need to know is that Set doesn’t allow duplicates in Java. Which means if you have added an element into Set and trying to insert duplicate element again, it will not be allowed
for (String name : names)
{
if (set.add(name) == false)
{ // your duplicate element }
}