Write a Comparator “MyStringComparator” that compares String objects of a partic
ID: 3811208 • Letter: W
Question
Write a Comparator “MyStringComparator” that compares String objects of a particular format. Each string is of a form such as "123456, Seattle, WA", beginning with a numeric token that is followed by additional text tokens. Your job is to treat the first tokens as integers and compare them in numerical order. You cannot simply compare them by using the strings’ compareTo method, since it would treat the numbers as text and not as integers. For example, "276453, Helena, MT" is greater than "9847, New York, NY". You can use a Scanner to tokenize the strings while comparing them. Please write “MyStringSortingClient” class with has main method and has the strings in an array which will use the above comparator “MyStringComparator“ to sort them and also print the sorted strings one in each line.
Explanation / Answer
Hi, Please find my implementation.
Please let me know in case of issue .
###############################################
import java.util.Comparator;
public class MyStringComparator implements Comparator<String> {
@Override
public int compare(String o1, String o2) {
// TODO Auto-generated method stub
String s1 = o1.substring(0, o1.indexOf(','));
String s2 = o2.substring(0, o2.indexOf(','));
return s1.compareTo(s2);
}
}
#####################################################
import java.util.ArrayList;
import java.util.Collections;
public class MyStringSortingClient {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("123456, Seattle, WA");
list.add("9847, New York, NY");
list.add("276453, Helena, MT");
MyStringComparator myComparator = new MyStringComparator();
System.out.println(list);
Collections.sort(list,myComparator );
System.out.println(list);
}
}
/*
Sample run:
[123456, Seattle, WA, 9847, New York, NY, 276453, Helena, MT]
[123456, Seattle, WA, 276453, Helena, MT, 9847, New York, NY]
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.