Reputation: 197
I've created a list in java as following :
1 bbbb london
1.1 aaaa nyc
1.10 cccc jaipur
...
1.2 test test
1.11 test1 test1
I need to sort it based on index 1,1.1,1.2 etc! These are string values.
Like:
1 bbbb london
1.1 aaaa nyc
1.2 test test
...
1.10 cccc jaipur
1.11 test1 test1
How can i do that?
Initially the index was float but in-order to get 1.10 in list i changed index to string so Collection.sort(list)
doesnt give output as expected.
My purpose is like to create a numbered bullets like
1 Helo
1.1 helo1
1.2 helo2
1.3 hello3
2 Test
2.1 Test1
2.2 Test2
3 World
Any help please?
Upvotes: 0
Views: 1748
Reputation: 2148
Try this. This should work. Main logic is in compareTo
method.
import java.util.ArrayList;
import java.util.Collections;
public class Sort
{
public static void main(String[] args)
{
ArrayList<Entry> entries = new ArrayList<>();
entries.add(new Entry("1", "bbbb london"));
entries.add(new Entry("1.1", "aaaa nyc"));
entries.add(new Entry("1.10", "cccc jaipur"));
entries.add(new Entry("1.2", "test test"));
entries.add(new Entry("1.11", "test1 test1"));
Collections.sort(entries);
for (Entry e : entries)
{
System.out.println(e);
}
}
}
class Entry implements Comparable<Entry>
{
String index;
String value;
int major;
int minor;
Entry(String index, String value)
{
this.index = index;
this.value = value;
String[] array = index.split("\\.");
if (array.length == 2)
{
major = Integer.valueOf(array[0]);
minor = Integer.valueOf(array[1]);
}
else if (array.length == 1)
{
major = Integer.valueOf(array[0]);
}
else
{
throw new IllegalArgumentException("Invalid index : " + index);
}
}
@Override
public int compareTo(Entry otherEntry)
{
if (this.major < otherEntry.major)
{
return -1;
}
else if (this.major > otherEntry.major)
{
return 1;
}
else
{
if (this.minor < otherEntry.minor)
{
return -1;
}
else if (this.minor > otherEntry.minor)
{
return 1;
}
else
{
return 0;
}
}
}
@Override
public String toString()
{
return index + " " + value;
}
}
Upvotes: -1
Reputation: 15443
Given the list :
List<String> list = Arrays.asList("1.32 bbbb london", "21.1 aaaa nyc",
"100.10 cccc jaipur", "1.2 test test",
"1.11 test1 test1");
You can write your own custom comparator as shown below :
Collections.sort(list, new Comparator<String>() {
public int compare(String o1, String o2) {
return Float.compare(Float.parseFloat(o1.split(" ")[0]),
Float.parseFloat(o2.split(" ")[0]));
}
});
Here, we split the String by " "
and fetch the floating part of the string which happens to be the first index of the array. Now we parse it to a float and compare it with the second string.
If you are on java-8
you could do it one line :
Collections.sort(list, (o1, o2) ->
Float.compare(Float.parseFloat(o1.split(" ")[0]), Float.parseFloat(o2.split(" ")[0])));
Upvotes: 5