4

I have an ArrayList of version strings that I would like to sort so that the newest is the first listed.

ArrayList<String> items = new ArrayList<String>();
items.add("4.1.0");
items.add("4.1.1");
items.add("4.1");
items.add("5.1");
items.add("4.0.1");

My Expected Output is:

5.1
4.1.1
4.1.0
4.1
4.0.1

When considering the values as Integers, "4.0.1" is greater than "4.1", which is not true in the case of versions.

I am thinking of using a Comparator Interface for each major, minor and incremental version. Is there an easier way of doing this?

Mitch Pomery
  • 493
  • 4
  • 14
Upen
  • 1,388
  • 1
  • 22
  • 49

3 Answers3

3

Upen, There's a ComparableVersion class from maven for the same.

Also, take a look at this SO conversation

I hope this solves your problem.

Community
  • 1
  • 1
Ravindra Mijar
  • 1,282
  • 2
  • 9
  • 17
  • 1
    Works wonders. DefaultArtifactVersion version = new DefaultArtifactVersion("4.1.2");. Thanks much. – Upen Jan 12 '16 at 21:25
1

I faced a similar problem where I had to compare versions of the same library, besides number I had to make sure that the comparison took into account SNAPSHOT vs release point versions. After trying to come up with all the corner cases I decided not to re-invent the wheel and decided to look for a trusted implementation to solve the same problem.

I found the maven ComparableVersion source code and put it in my project since I didn't want to depend in that maven jar in my code.

Hope it helps for you!

Jose Luis

jbarrueta
  • 4,907
  • 2
  • 20
  • 21
0

Read some about maven version & Project Dependencies from Maven: The Complete Reference book

http://books.sonatype.com/mvnref-book/reference/pom-relationships-sect-project-dependencies.html

amkz
  • 568
  • 3
  • 9
  • 31