I'm having array of list like this
array list={Rank,Shyam,"Sores","Hintus",Ander}
I'm using Collections.sort(arraylist);
I'm getting like this:
"Hintus"
"Sores"
Ander
Rank
I'm getting strings with special characters before any other string in my list.
But I want to get results like this:
Ander
Rank
"Hintus"
"Sores"
How do I get desired order?
Specify a Comparator that ignores them... note that this may be costly.
Collectons.sort(list, new Comparator<String>() {
public int compare(final String a, final String b) {
return a.replace("\"", "").compareTo(b.replace("\"", ""));
}
});
you can create a comparator by your own, and in comparator, write your sorting criteria. and then sort the arraylist using this comparator.
Related
I want to sort an ArrayList of type String using a comparator. I have only found examples on how to do it if an ArrayList stores objects.
I have an ArrayList of strings that have 10 symbols and last 5 of those symbols are digits that form a number. I want to solve an array list in ascending order of those numbers that are at the end of each string. How can I do that?
Thanks!
This is one way to accomplish your task; sorted accepts a Comparator object.
List<String> result = myArrayList.stream().sorted(Comparator.comparingInt(e -> Integer.parseInt(e.substring(5))))
.collect(Collectors.toList());
or simply:
myArrayList.sort(Comparator.comparingInt(e -> Integer.parseInt(e.substring(5))));
Collections.sort can sort you a list with a Comparator. Plus you need String.substring:
Collections.sort(list, new Comparator<String>(){
#Override
public int compare(String o1, String o2) {
return o1.substring(5).compareTo(o2.substring(5));
}
});
Collections.sort(list, String::compareTo);
The above code does the job.
If you want more control, you could use/chain with one of the static methods available in the Comparator Interface.
Collectios.sort(list, Comparator.comparing(String::CompareTo).thenComparingInt(String::length));
I have a List<String> list which is initialized to an arrayList. That is,
List<String>list = new ArrayList();
It has the following elements.
[1,bread, 1,turkey, 10,potato, 11,plum, 12,carrot, 2,milk, 2,rice]
I would like to sort the list so that the numbers are in ascending order. For example,
[1,bread,1 turkey,2,milk,2,rice,10,potato,11,plum,12,carrot]
How can I do that?
Java is an Object-Oriented language, and you should use it.
So, create a new class with two fields: int and String.
Now parse your strings and create objects, i.e. 1,bread is parsed into the int value 1, and the String value bread.
Next, make your class implement Comparable, and implement the compareTo method to order the objects by the int value.
Finally, now that List<String> was converted to List<MyObj>, call Collections.sort(list).
You're not trying to sort the elements in the List--you're trying to sort pairs of elements. You can't do that with a simple sort. What you'll need to do is:
Define a class with two fields, an int and a String. Make the class implement Comparable.
Define a comparator for the class that compares the int fields to get the order you want. You'll have to decide what your comparator will do if the int fields are equal (do you want the String fields to be in ascending order?)
Create a List<YourClass> whose size is half the size of the original list, by going through the source list in pairs, something like
for (int i = 0; i < list.size() - 1; i += 2) {
create a YourClass by converting list.get(i) to an int, and using list.get(i+1) as the String field
}
Sort the new list
If desired, recreate a List<String> by going through the List<YourClass> and adding a String conversion of the int, followed by the String field from YourClass, to the new list.
I don't know what you're planning to do with the String list, but in most cases it will make your program easier if you create a List<YourClass> list as soon as possible, and work with YourClass objects throughout the rest of the program
The simple answer is that you could provide a custom Comparator which understands the structure of each individual String element and can parse and compare them properly. Something like this:
#Test
public void testShouldSortByNumber() {
// Arrange
List<String> list = Arrays.asList("1,bread", "1,turkey", "10,potato", "11,plum", "12,carrot", "2,milk", "2,rice");
final List<String> EXPECTED_LIST = Arrays.asList("1,bread", "1,turkey", "2,milk", "2,rice", "10,potato", "11,plum", "12,carrot");
// Act
Collections.sort(list, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
try {
int i1 = Integer.parseInt(o1.split(",")[0]);
int i2 = Integer.parseInt(o2.split(",")[0]);
// If the numbers are equal, could order by alpha on the second part of the string split
return i1 < i2 ? -1 : i1 == i2 ? 0 : 1;
} catch (Exception e) {
// Lots of possible errors above -- NPE, NFE, invalid string format, etc.
e.printStackTrace();
}
return 0;
}
});
// Assert
assert list.equals(EXPECTED_LIST);
}
The more complex answer is that you should better define your problem -- what should the result be if an element is empty or null, if the numbers are equal are the other strings compared lexicographically or is it irrelevant?
You may also want to use a different data structure -- if the content of each element is really two different logical concepts, a tuple or class may be correct. Or, you may want to use a SortedMap (of which TreeMap is probably the best implementation here) where the key is the "ingredient" and the value is the "count" (or "cost", I don't have any context on the numerical value).
You can also enhance the code above with a lambda if you have access to JDK 8+.
I have an ArrayList of semicolon separated values that needs to be sorted by the second field of each of the ArrayList elements.
Each of the elements of the array list have the form:
field1;field2;field3;field4
and need to be sorted by field.2 Is there a way to do this without having to create a temporary array, switch field1 and field2, sort that array, and then switch field1 and field2 again?
Thank you for any help you might be able to offer
This code will do it for you:
Collections.sort(list, new Comparator<String>(){
#Overide
public int compare(String s1, String s2){
return s1.split(";")[1].compareTo(s2.split(";")[1]);
}
});
You need to write a Comparator<String> that extracts the second field and compares it. No intermediate array needed. Just a bit of substring/indexof/regex/substringBetween.
You can do this, to create own Comparator and use Collections.sort something like
Collections.sort(yourArrayList, new Comparator<String>(){
#Overide
public int compare(String s1, String s2){
String s1Field2, s2Field2;
// Do your extracting of field 2 for each String
s1Field2 = s1.split(";")[1];
s2Field2 = s2.split(";")[1];
// You may also want to add to this to ensure that the original strings
// do contain a 'field2'
return s1Field2.compareTo(s2Field2);
}
});
I have a TreeTable and would like to perform the sort by number and alphabetically when clicking on header.
Example:
On a first click, I have to check that the column content is sorted by number
If I click on another column that contains String data, I have to check that column content is sorted alphabetically.
Are there known functions that could I use?
I've used Collections for sorting number , but how do I can make the sort alphabetically ?
Collections.sor(myList) is OK for sorting by number but I would sort data alphabetically.
thanks
This can easily be done via Collections.sort(...). Create a copy of your list, sort it and check if they are equal.
Example:
List <String> copy = new ArrayList <String>(original);
Collections.sort(copy);
assertEquals(copy, original);
This can be done, if the elements in the list are comparable (i.e. are of type T implements Comparable <T>). Strings are comparable, and their default comparator sorts them alphabetically (though upper-case are always comes before lower-case)
You may also provide a Comparator for a more flexible sorting.
Here is a more complicated example.
List <String> unholyBible = new ArrayList <String>();
unholyBible.add("armageddon");
unholyBible.add("abyss");
unholyBible.add("Abaddon");
unholyBible.add("Antichrist");
Collections.sort(unholyBible);
System.out.println(unholyBible);
This will print us [Abaddon, Antichrist, abyss, armageddon]. This is because default comparation is case-sensitive. Lets fix it:
List <String> unholyBible = new ArrayList <String>();
unholyBible.add("armageddon");
unholyBible.add("abyss");
unholyBible.add("Abaddon");
unholyBible.add("Antichrist");
Collections.sort(unholyBible, new Comparator <String>() {
public int compare(String o1, String o2){
return o1.compareToIgnoreCase(o2);
}
});
System.out.println(unholyBible);
This one prints [Abaddon, abyss, Antichrist, armageddon].
Now you may worship Satan in strict alphabetical order.
See also
Comparator API
Collections.sort(List, Comparator)
I have a scenario where I have two ArrayLists
ArrayList<String> sortedArrayList
ArrayList<String> unSortedArrayList
I have to sort unSortedArrayList depending on the sortedArrayList.
i.e, sortedArrayList is already sorted, now based on sortedArrayList, I have to sort unSortedArrayList.
unSortedArrayList size is <= to the size of sortedArrayList.
Is there a Java API for that?
Any help is appreciated.
Using Google Guava's excellent Ordering class:
Collections.sort(unSortedArrayList, Ordering.explicit(sortedArrayList));
EDIT You can also do
List<whatever> sortedList = Ordering.explicit(sortedArrayList).immutableSortedCopy(unsortedArrayList);
As I understand what you have is that each element in list 1 has a corresponding element in list 2, and you want list 2 sorted into the order of the 'corresponding' elements. Your best approach is to create an object to contain both Strings:
class StringPair {
String s1;
String s2;
}
Now make an array list of StringPairs and sort it based on the value of s1.
List<String> newSortedList = new ArrayList<String>();
for(String currentSortedStr:sortedList){
if(unsortedList.size==0)break;
if(unsortedList.remove(currentSortedStr)){
newSortedList.add(currentSortedStr);
}
}
You can do something like this if you mean what #Sam Dufel says in the comment
As far as I know there is not such API method for this case.
This is not gonna take care of duplicates. remove will remove only the first occurence of that object. At the if the unsorted list size is greater than 0, you can say it contains duplicates. And if you need duplicates as well, you may wanna add some code to handle that case as well.
or if you mean the normal sorting;
Collections.sort(List<T>) will do the sorting for you.
Another way of doing it;
Collections.sort(unsortedList,new CustomComparator(sortedList));
public class CustomComparator implements Comparator<String>{
private List<String> sortedList;
public CustomComparator(List<String> sortedList){
this.sortedList = sortedList;
}
#Override
public int compare(String o1, String o2) {
return sortedList.indexOf(o1)-sortedList.indexOf(o2);
}
}
Although your question is not clear enough I think that the following will help you.
You can use Collections.sort() to sort list. If you need some custom modification to sort mechanism implement your own Comparator and use 2 args version of this method: Collections.sort(list, comparable)