Thursday, June 29, 2017

Combined Number using Java 8

Following is  a function, accepting a list of non negative integers, and returning their largest possible combined number as a string. For example

given [50, 2, 1, 9] it returns "95021"    (9 + 50 + 2 + 1)
given [5, 50, 56]   it returns "56550"    (56 + 5 + 50)
given 420, 42, 423] it returns "42423420" (42 + 423 + 420)

Source [https://blog.svpino.com/about]
  
import java.util.Arrays;

public class CombineNumber{
    public static void main(String... args){
        System.out.println(combine(50, 2, 1, 9));
        System.out.println(combine(5, 50, 56));
        System.out.println(combine(420, 42, 423));
    }
    public static String combine(int... numbers){
        return Arrays.stream(numbers).boxed().map(x->x.toString()).sorted((a,b)->(b+a).compareTo(a+b)).reduce(String::concat).get();
    }
}

Output:
95021
56550
42423420

No comments:

Post a Comment