To sort two lists of strings in Java and compare them, you can follow these steps:
Create two lists of strings:
List<String> list1 = Arrays.asList("apple", "banana", "cherry", "date");
List<String> list2 = Arrays.asList("cherry", "date", "apple", "banana");
Use the Collections.sort()
method to sort the lists:
Collections.sort(list1);
Collections.sort(list2);
Compare the sorted lists using the equals()
method:
boolean equalLists = list1.equals(list2);
If the boolean equalLists
is true
, then the two lists are equal, otherwise they are not.
Here is the complete code:
import java.util.*;
public class SortAndCompareLists {
public static void main(String[] args) {
// Create two lists of strings
List<String> list1 = Arrays.asList("apple", "banana", "cherry", "date");
List<String> list2 = Arrays.asList("cherry", "date", "apple", "banana");
// Sort the lists
Collections.sort(list1);
Collections.sort(list2);
// Compare the sorted lists
boolean equalLists = list1.equals(list2);
// Print the result
if (equalLists) {
System.out.println("The two lists are equal.");
} else {
System.out.println("The two lists are not equal.");
}
}
}
Asked: 2022-08-30 11:00:00 +0000
Seen: 7 times
Last updated: Aug 14 '21