Search Bar

Java 8 Sort a List of Strings based on the second character


Java 8 stream API interview question: Sort a List of Strings based on the second character.

 

Hello Programmers,

Today we are going to look at one of the Java interview questions using Java 8, I have been asked this interview question in one of the Client rounds. 

Question: Write a Java 8 Program for sorting a List of Strings based on the second character in the string.

JAVA 8 Stream API Interview Coding Questions Sort a List of Strings based on the second character.
JAVA 8 Stream API Interview Coding Questions Sort a List of Strings based on the second character.


Solution 1: 

package test.amol;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class InterviewPrep {

public static void main(String[] args) {

List<String> names =
Arrays.asList("Amol", "Aniket", "Avinash", "Ram", "Sham", "Vishal");

Collections.sort(names, (s1, s2) -> {
String sb1 = s1.substring(1);
String sb2 = s2.substring(1);
return sb1.compareTo(sb2);
});

System.out.println(names);

}

}

Solution 2:

package test.amol;

import java.util.Arrays;
import java.util.List;

public class InterviewPrep {

public static void main(String[] args) {

List<String> names =
Arrays.asList("Amol", "Aniket", "Avinash", "Ram", "Sham", "Vishal");

names.sort((s1, s2) -> Character.compare(s1.charAt(1), s2.charAt(1)));

System.out.println(names);

}

}

Solution 3:

package test.amol;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class InterviewPrep {

public static void main(String[] args) {

List<String> names =
Arrays.asList("Amol", "Aniket", "Avinash", "Ram", "Sham", "Vishal");

names.stream()
.sorted(Comparator.comparing(s -> s.charAt(1)))
.forEach(System.out::println);

}

}



Post a Comment

0 Comments