Ask Your Question
1

How can I sort two lists of strings in Java and compare them?

asked 2022-08-30 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-08-14 13:00:00 +0000

plato gravatar image

To sort two lists of strings in Java and compare them, you can follow these steps:

  1. Create two lists of strings:

    List<String> list1 = Arrays.asList("apple", "banana", "cherry", "date");
    List<String> list2 = Arrays.asList("cherry", "date", "apple", "banana");
    
  2. Use the Collections.sort() method to sort the lists:

    Collections.sort(list1);
    Collections.sort(list2);
    
  3. 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.");
        }
    }
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-08-30 11:00:00 +0000

Seen: 7 times

Last updated: Aug 14 '21