Find the second smallest elements in an array.

There are multiple way to find the second smallest elements in an array.

from java 8 min method :-

  • First we streaming the list of data.
  • From skip(1) method we are taking the second position element.
  • Integer::compare this method sort the element in ascending order.
  • To get method we pick the element for print.

from sort method :-

  • Collections.sort() method sorting the elements in ascending order.
  • l.get(1) method take the element of index 1 position and print.

from for loop method :-

  • Here we traverse the element from two for loop.
  • Take one temp variable for storing element.
  • Sorting the array data inside if condition.
  • Returning the 2nd element from array a at index position 1 and print.
				
					import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class SecondMinElement {
	public static void main(String[] args) {

		// from java 8 min method
		List<Integer> l = Arrays.asList(2, 56, 4, 70, 6);
		int i = l.stream().skip(1).min(Integer::compare).get();
		System.out.println("second min element from java 8 min method :- " + i);

		// from sort method
		Collections.sort(l);
		System.out.println("from sort method :- " + l.get(1));

		// for loop method
		int a[] = { 2, 56, 4, 70, 6 };
		int temp;
		for (int m = 0; m < a.length; m++) {
			for (int n = m + 1; n < a.length; n++) {
				if (a[m] > a[n]) {
					temp = a[m];
					a[m] = a[n];
					a[n] = temp;
				}
			}
		}
		System.out.println("from for loop method :- " + a[1]);
	}
}
				
			

Output :-
second min element from java 8 min method :- 4
from sort method :- 4
from for loop method :- 4