Scroll to top

How to sort list of String or Integer in java

Here we will learn to code how to sort a List of Integer and String.
To know how to sort List of custom class Look Here.

package com.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/*
 * Here we will learn how to sort item in ArrayList
 */
public class SortItemsInArrayList {

	public static void main(String args[]) {
		List<Integer> listInt = new ArrayList<Integer>();
		List<String> listString = new ArrayList<String>();

		listInt.add(12);
		listInt.add(4);
		listInt.add(84);
		listInt.add(11);

		listString.add("Hello");
		listString.add("How");
		listString.add("Hi");

		System.out.println("Before Sorting List of Integer");

		// Here we are using advanced for loop. It can be used with list as list is Iterable
		for (int str : listInt) {
			System.out.println("Value in integer list:" + str);
		}

		Collections.sort(listInt);

		System.out.println("After sorting List of Integer");

		for (int str : listInt) {
			System.out.println("Value in integer list:" + str);
		}

		System.out.println("Before sorting List of String");
		for (String str : listString) {
			System.out.println("Value in string list:" + str);
		}

		Collections.sort(listString);

		System.out.println("After sorting List of String");

		for (String str : listString) {
			System.out.println("Value in list:" + str);
		}

	}
}

 

Author avatar
JBT
https://javabeginnerstutorial.com/

Post a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.