Sobes.tech
Junior

How to sort a list of strings using a lambda expression?

sobes.tech AI

Answer from AI

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

public class StringSortExample {

    public static void main(String[] args) {
        List<String> strings = new ArrayList<>();
        strings.add("banana");
        strings.add("apple");
        strings.add("cherry");

        // Sorting the list of strings using a lambda expression
        Collections.sort(strings, (str1, str2) -> str1.compareTo(str2));

        // Printing the sorted list
        for (String s : strings) {
            System.out.println(s);
        }

        // Alternative method using the sort method from List
        List<String> anotherList = new ArrayList<>();
        anotherList.add("orange");
        anotherList.add("grape");
        anotherList.add("kiwi");

        anotherList.sort((str1, str2) -> str1.compareTo(str2));

        System.out.println("\nSorted another list:");
        for (String s : anotherList) {
            System.out.println(s);
        }
    }
}