Version Comparator/Sorter

package com.scm.cba.vercomp; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * A Version class that implements a custom version comparator for easy sorting * * @author Soumava Das * @version 1.0 * @since 2017-08-09 */ public class Version implements Comparable<Version> { /** * @param args */ String ver; String flag; Version(String ver) { this.ver = ver; } Version() { } public static void main(String[] args) { List<Version> list = new ArrayList<Version>(); list.add(new Version("1.2")); list.add(new Version("1.1.1.5")); list.add(new Version("0")); list.add(new Version("1.2.1.5.7")); list.add(new Version("1")); list.add(new Version("1.2.5")); list.add(new Version("3.8")); list.add(new Version("1.2.1.7")); System.out.println("\nIN INPUT ORDER:\n---------------"); for(Version ver: list){ System.out.print(ver.getVer()+" | "); } System.out.println(); /*list.sort(VersionComparator); System.out.println("\nIN ASCENDING ORDER:\n--------------------"); for(Version ver: list){ System.out.print(ver.getVer()+" | "); }*/ System.out.println("\nMAX: "+Collections.max(list,VersionComparator).getVer()); } @Override public int compareTo(Version versort) { List<String> ver1Split = Arrays.asList(this.ver.split(".")); List<String> ver2Split = Arrays.asList(versort.getVer().split(".")); int returnVal = 0; if (ver1Split.size() > ver2Split.size()) ver2Split = padWithZero(ver2Split, ver1Split.size() - ver2Split.size()); else ver1Split = padWithZero(ver1Split, ver2Split.size() - ver1Split.size()); for (int i = 0; i < ver1Split.size(); i++) { if (Integer.parseInt(ver1Split.get(i)) == Integer .parseInt(ver2Split.get(i))) continue; if (Integer.parseInt(ver1Split.get(i)) > Integer.parseInt(ver2Split .get(i))) { returnVal = 1; } else returnVal = -1; } return returnVal; } public static Comparator<Version> VersionComparator = new Comparator<Version>() { public int compare(Version ver1, Version ver2) { String verStr1 = ver1.getVer(); String verStr2 = ver2.getVer(); // ascending order return verStr1.compareTo(verStr2); // descending order //return verStr2.compareTo(verStr1); } }; public static List<String> padWithZero(List<String> ver, int noz) { for (int i = 1; i <= noz; i++) { ver.add("0"); } return ver; } public String getVer() { return ver; } public String getFlag() { return flag; } public void setFlag(String flag) { this.flag = flag; } }
A Version class that implements a custom version comparator for easy sorting

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.