Sort List using Lambda expression











up vote
1
down vote

favorite












How do i sort this using Lambda expression?
I am suppose to sort the first 7 numbers and exclude the last number. I saw that IntStream.concat can be used but i need to use Lambda expression to sort.



     Random random = new Random();
List <Integer> lucky = random.ints (1, 64)
.distinct()
.limit(8)
.boxed()
.sorted()
.collect(Collectors.toList());









share|improve this question






















  • Sort based on what?
    – Nicholas K
    Nov 7 at 18:22










  • Why insisting on using a lambda?
    – Sweeper
    Nov 7 at 18:22










  • Do you need to generate random ints and sort them in one expression or can it be done in 2 expressions?
    – syntagma
    Nov 7 at 18:27










  • @NicholasK sort based on ascending order.
    – New Pea
    Nov 7 at 18:52












  • @Sweeper Preferably lambda as we are required to implement lambda expression
    – New Pea
    Nov 7 at 18:52















up vote
1
down vote

favorite












How do i sort this using Lambda expression?
I am suppose to sort the first 7 numbers and exclude the last number. I saw that IntStream.concat can be used but i need to use Lambda expression to sort.



     Random random = new Random();
List <Integer> lucky = random.ints (1, 64)
.distinct()
.limit(8)
.boxed()
.sorted()
.collect(Collectors.toList());









share|improve this question






















  • Sort based on what?
    – Nicholas K
    Nov 7 at 18:22










  • Why insisting on using a lambda?
    – Sweeper
    Nov 7 at 18:22










  • Do you need to generate random ints and sort them in one expression or can it be done in 2 expressions?
    – syntagma
    Nov 7 at 18:27










  • @NicholasK sort based on ascending order.
    – New Pea
    Nov 7 at 18:52












  • @Sweeper Preferably lambda as we are required to implement lambda expression
    – New Pea
    Nov 7 at 18:52













up vote
1
down vote

favorite









up vote
1
down vote

favorite











How do i sort this using Lambda expression?
I am suppose to sort the first 7 numbers and exclude the last number. I saw that IntStream.concat can be used but i need to use Lambda expression to sort.



     Random random = new Random();
List <Integer> lucky = random.ints (1, 64)
.distinct()
.limit(8)
.boxed()
.sorted()
.collect(Collectors.toList());









share|improve this question













How do i sort this using Lambda expression?
I am suppose to sort the first 7 numbers and exclude the last number. I saw that IntStream.concat can be used but i need to use Lambda expression to sort.



     Random random = new Random();
List <Integer> lucky = random.ints (1, 64)
.distinct()
.limit(8)
.boxed()
.sorted()
.collect(Collectors.toList());






java sorting lambda






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 7 at 18:21









New Pea

326




326












  • Sort based on what?
    – Nicholas K
    Nov 7 at 18:22










  • Why insisting on using a lambda?
    – Sweeper
    Nov 7 at 18:22










  • Do you need to generate random ints and sort them in one expression or can it be done in 2 expressions?
    – syntagma
    Nov 7 at 18:27










  • @NicholasK sort based on ascending order.
    – New Pea
    Nov 7 at 18:52












  • @Sweeper Preferably lambda as we are required to implement lambda expression
    – New Pea
    Nov 7 at 18:52


















  • Sort based on what?
    – Nicholas K
    Nov 7 at 18:22










  • Why insisting on using a lambda?
    – Sweeper
    Nov 7 at 18:22










  • Do you need to generate random ints and sort them in one expression or can it be done in 2 expressions?
    – syntagma
    Nov 7 at 18:27










  • @NicholasK sort based on ascending order.
    – New Pea
    Nov 7 at 18:52












  • @Sweeper Preferably lambda as we are required to implement lambda expression
    – New Pea
    Nov 7 at 18:52
















Sort based on what?
– Nicholas K
Nov 7 at 18:22




Sort based on what?
– Nicholas K
Nov 7 at 18:22












Why insisting on using a lambda?
– Sweeper
Nov 7 at 18:22




Why insisting on using a lambda?
– Sweeper
Nov 7 at 18:22












Do you need to generate random ints and sort them in one expression or can it be done in 2 expressions?
– syntagma
Nov 7 at 18:27




Do you need to generate random ints and sort them in one expression or can it be done in 2 expressions?
– syntagma
Nov 7 at 18:27












@NicholasK sort based on ascending order.
– New Pea
Nov 7 at 18:52






@NicholasK sort based on ascending order.
– New Pea
Nov 7 at 18:52














@Sweeper Preferably lambda as we are required to implement lambda expression
– New Pea
Nov 7 at 18:52




@Sweeper Preferably lambda as we are required to implement lambda expression
– New Pea
Nov 7 at 18:52












2 Answers
2






active

oldest

votes

















up vote
3
down vote



accepted










The requirement of "use a lambda expression" is quite weird. I can fulfil this requirement simply by replace the .limit call with



.limit(((IntSupplier)() -> 8).getAsInt())


Look! I've used a lambda there! () -> 8. And then you can move on to sort the problem with concat as you said.



Obviously, this is not what you meant.



If you want to put a lambda into the sort method to sort the first 7 integers and then always leave the 8th at the end, you could do something like this:



Random random = new Random();
List<Integer> unsorted = random.ints(1, 64)
.distinct()
.limit(8)
.boxed()
.collect(Collectors.toList());

// here you need to get the last element that you don't want to sort
int last = unsorted.get(unsorted.size() - 1);
// here is the lambda
List<Integer> sorted = unsorted.stream().sorted((x, y) -> {
if (Integer.compare(x, y) == 0) {
return 0;
}
// if any one of the arguments is the last one...
if (last == x) {
return 1;
}
if (last == y) {
return -1;
}
return Integer.compare(x, y);
}).collect(Collectors.toList());
// you can also use "List.sort" with the same lambda


Note that I personally find this sorted method call very unreadable. I can't see at first glance that you are trying to sort everything but the last. In terms of readability, using concat would be better.






share|improve this answer























  • Surprisingly, I don't think this implementation of Comparator violates the general contract! I so thought it was going to violate the contract.
    – Sweeper
    Nov 7 at 19:07










  • I was planning on using Collections.sort(lucky.sublist(0,6)) as i don't see the point in using Lambda just to sort unless i misunderstood what my prof meant when he said "I do no expect you to implement some sorting methods to sort them. You are working on functional programming; Lambda can help you to achieve this target. "
    – New Pea
    Nov 7 at 19:16










  • @KevinChee well, you aren’t really writing a sorting method. The lambda only compares two integers.
    – Sweeper
    Nov 7 at 19:33


















up vote
2
down vote













You can use lambda as a second parameter to Collections.sort(), providing sublist as the first parameter:



Collections.sort(lucky.subList(0, lucky.size()-1), 
(i1, i2) -> i1.compareTo(i2));


This will be equivalent to Collections.sort(lucky.subList(0, lucky.size()-1)), so you don't really need this lambda expression here.



Another way to do it (not an efficient one) would be using Stream.concat():



List<Integer> sorted = Stream.concat(
lucky.stream()
.filter(elem -> !elem.equals(lucky.get(lucky.size() - 1))).sorted(),
Stream.of(lucky.get(lucky.size() - 1)))
.collect(Collectors.toList());


Note that I am filtering items in the first stream based on value, not the index, as items in lucky list are distinct. This could be done based on the index, though that would make performance of that sorting even worse.






share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














     

    draft saved


    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53195505%2fsort-listinteger-using-lambda-expression%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    3
    down vote



    accepted










    The requirement of "use a lambda expression" is quite weird. I can fulfil this requirement simply by replace the .limit call with



    .limit(((IntSupplier)() -> 8).getAsInt())


    Look! I've used a lambda there! () -> 8. And then you can move on to sort the problem with concat as you said.



    Obviously, this is not what you meant.



    If you want to put a lambda into the sort method to sort the first 7 integers and then always leave the 8th at the end, you could do something like this:



    Random random = new Random();
    List<Integer> unsorted = random.ints(1, 64)
    .distinct()
    .limit(8)
    .boxed()
    .collect(Collectors.toList());

    // here you need to get the last element that you don't want to sort
    int last = unsorted.get(unsorted.size() - 1);
    // here is the lambda
    List<Integer> sorted = unsorted.stream().sorted((x, y) -> {
    if (Integer.compare(x, y) == 0) {
    return 0;
    }
    // if any one of the arguments is the last one...
    if (last == x) {
    return 1;
    }
    if (last == y) {
    return -1;
    }
    return Integer.compare(x, y);
    }).collect(Collectors.toList());
    // you can also use "List.sort" with the same lambda


    Note that I personally find this sorted method call very unreadable. I can't see at first glance that you are trying to sort everything but the last. In terms of readability, using concat would be better.






    share|improve this answer























    • Surprisingly, I don't think this implementation of Comparator violates the general contract! I so thought it was going to violate the contract.
      – Sweeper
      Nov 7 at 19:07










    • I was planning on using Collections.sort(lucky.sublist(0,6)) as i don't see the point in using Lambda just to sort unless i misunderstood what my prof meant when he said "I do no expect you to implement some sorting methods to sort them. You are working on functional programming; Lambda can help you to achieve this target. "
      – New Pea
      Nov 7 at 19:16










    • @KevinChee well, you aren’t really writing a sorting method. The lambda only compares two integers.
      – Sweeper
      Nov 7 at 19:33















    up vote
    3
    down vote



    accepted










    The requirement of "use a lambda expression" is quite weird. I can fulfil this requirement simply by replace the .limit call with



    .limit(((IntSupplier)() -> 8).getAsInt())


    Look! I've used a lambda there! () -> 8. And then you can move on to sort the problem with concat as you said.



    Obviously, this is not what you meant.



    If you want to put a lambda into the sort method to sort the first 7 integers and then always leave the 8th at the end, you could do something like this:



    Random random = new Random();
    List<Integer> unsorted = random.ints(1, 64)
    .distinct()
    .limit(8)
    .boxed()
    .collect(Collectors.toList());

    // here you need to get the last element that you don't want to sort
    int last = unsorted.get(unsorted.size() - 1);
    // here is the lambda
    List<Integer> sorted = unsorted.stream().sorted((x, y) -> {
    if (Integer.compare(x, y) == 0) {
    return 0;
    }
    // if any one of the arguments is the last one...
    if (last == x) {
    return 1;
    }
    if (last == y) {
    return -1;
    }
    return Integer.compare(x, y);
    }).collect(Collectors.toList());
    // you can also use "List.sort" with the same lambda


    Note that I personally find this sorted method call very unreadable. I can't see at first glance that you are trying to sort everything but the last. In terms of readability, using concat would be better.






    share|improve this answer























    • Surprisingly, I don't think this implementation of Comparator violates the general contract! I so thought it was going to violate the contract.
      – Sweeper
      Nov 7 at 19:07










    • I was planning on using Collections.sort(lucky.sublist(0,6)) as i don't see the point in using Lambda just to sort unless i misunderstood what my prof meant when he said "I do no expect you to implement some sorting methods to sort them. You are working on functional programming; Lambda can help you to achieve this target. "
      – New Pea
      Nov 7 at 19:16










    • @KevinChee well, you aren’t really writing a sorting method. The lambda only compares two integers.
      – Sweeper
      Nov 7 at 19:33













    up vote
    3
    down vote



    accepted







    up vote
    3
    down vote



    accepted






    The requirement of "use a lambda expression" is quite weird. I can fulfil this requirement simply by replace the .limit call with



    .limit(((IntSupplier)() -> 8).getAsInt())


    Look! I've used a lambda there! () -> 8. And then you can move on to sort the problem with concat as you said.



    Obviously, this is not what you meant.



    If you want to put a lambda into the sort method to sort the first 7 integers and then always leave the 8th at the end, you could do something like this:



    Random random = new Random();
    List<Integer> unsorted = random.ints(1, 64)
    .distinct()
    .limit(8)
    .boxed()
    .collect(Collectors.toList());

    // here you need to get the last element that you don't want to sort
    int last = unsorted.get(unsorted.size() - 1);
    // here is the lambda
    List<Integer> sorted = unsorted.stream().sorted((x, y) -> {
    if (Integer.compare(x, y) == 0) {
    return 0;
    }
    // if any one of the arguments is the last one...
    if (last == x) {
    return 1;
    }
    if (last == y) {
    return -1;
    }
    return Integer.compare(x, y);
    }).collect(Collectors.toList());
    // you can also use "List.sort" with the same lambda


    Note that I personally find this sorted method call very unreadable. I can't see at first glance that you are trying to sort everything but the last. In terms of readability, using concat would be better.






    share|improve this answer














    The requirement of "use a lambda expression" is quite weird. I can fulfil this requirement simply by replace the .limit call with



    .limit(((IntSupplier)() -> 8).getAsInt())


    Look! I've used a lambda there! () -> 8. And then you can move on to sort the problem with concat as you said.



    Obviously, this is not what you meant.



    If you want to put a lambda into the sort method to sort the first 7 integers and then always leave the 8th at the end, you could do something like this:



    Random random = new Random();
    List<Integer> unsorted = random.ints(1, 64)
    .distinct()
    .limit(8)
    .boxed()
    .collect(Collectors.toList());

    // here you need to get the last element that you don't want to sort
    int last = unsorted.get(unsorted.size() - 1);
    // here is the lambda
    List<Integer> sorted = unsorted.stream().sorted((x, y) -> {
    if (Integer.compare(x, y) == 0) {
    return 0;
    }
    // if any one of the arguments is the last one...
    if (last == x) {
    return 1;
    }
    if (last == y) {
    return -1;
    }
    return Integer.compare(x, y);
    }).collect(Collectors.toList());
    // you can also use "List.sort" with the same lambda


    Note that I personally find this sorted method call very unreadable. I can't see at first glance that you are trying to sort everything but the last. In terms of readability, using concat would be better.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 7 at 19:10

























    answered Nov 7 at 19:04









    Sweeper

    61k967134




    61k967134












    • Surprisingly, I don't think this implementation of Comparator violates the general contract! I so thought it was going to violate the contract.
      – Sweeper
      Nov 7 at 19:07










    • I was planning on using Collections.sort(lucky.sublist(0,6)) as i don't see the point in using Lambda just to sort unless i misunderstood what my prof meant when he said "I do no expect you to implement some sorting methods to sort them. You are working on functional programming; Lambda can help you to achieve this target. "
      – New Pea
      Nov 7 at 19:16










    • @KevinChee well, you aren’t really writing a sorting method. The lambda only compares two integers.
      – Sweeper
      Nov 7 at 19:33


















    • Surprisingly, I don't think this implementation of Comparator violates the general contract! I so thought it was going to violate the contract.
      – Sweeper
      Nov 7 at 19:07










    • I was planning on using Collections.sort(lucky.sublist(0,6)) as i don't see the point in using Lambda just to sort unless i misunderstood what my prof meant when he said "I do no expect you to implement some sorting methods to sort them. You are working on functional programming; Lambda can help you to achieve this target. "
      – New Pea
      Nov 7 at 19:16










    • @KevinChee well, you aren’t really writing a sorting method. The lambda only compares two integers.
      – Sweeper
      Nov 7 at 19:33
















    Surprisingly, I don't think this implementation of Comparator violates the general contract! I so thought it was going to violate the contract.
    – Sweeper
    Nov 7 at 19:07




    Surprisingly, I don't think this implementation of Comparator violates the general contract! I so thought it was going to violate the contract.
    – Sweeper
    Nov 7 at 19:07












    I was planning on using Collections.sort(lucky.sublist(0,6)) as i don't see the point in using Lambda just to sort unless i misunderstood what my prof meant when he said "I do no expect you to implement some sorting methods to sort them. You are working on functional programming; Lambda can help you to achieve this target. "
    – New Pea
    Nov 7 at 19:16




    I was planning on using Collections.sort(lucky.sublist(0,6)) as i don't see the point in using Lambda just to sort unless i misunderstood what my prof meant when he said "I do no expect you to implement some sorting methods to sort them. You are working on functional programming; Lambda can help you to achieve this target. "
    – New Pea
    Nov 7 at 19:16












    @KevinChee well, you aren’t really writing a sorting method. The lambda only compares two integers.
    – Sweeper
    Nov 7 at 19:33




    @KevinChee well, you aren’t really writing a sorting method. The lambda only compares two integers.
    – Sweeper
    Nov 7 at 19:33












    up vote
    2
    down vote













    You can use lambda as a second parameter to Collections.sort(), providing sublist as the first parameter:



    Collections.sort(lucky.subList(0, lucky.size()-1), 
    (i1, i2) -> i1.compareTo(i2));


    This will be equivalent to Collections.sort(lucky.subList(0, lucky.size()-1)), so you don't really need this lambda expression here.



    Another way to do it (not an efficient one) would be using Stream.concat():



    List<Integer> sorted = Stream.concat(
    lucky.stream()
    .filter(elem -> !elem.equals(lucky.get(lucky.size() - 1))).sorted(),
    Stream.of(lucky.get(lucky.size() - 1)))
    .collect(Collectors.toList());


    Note that I am filtering items in the first stream based on value, not the index, as items in lucky list are distinct. This could be done based on the index, though that would make performance of that sorting even worse.






    share|improve this answer

























      up vote
      2
      down vote













      You can use lambda as a second parameter to Collections.sort(), providing sublist as the first parameter:



      Collections.sort(lucky.subList(0, lucky.size()-1), 
      (i1, i2) -> i1.compareTo(i2));


      This will be equivalent to Collections.sort(lucky.subList(0, lucky.size()-1)), so you don't really need this lambda expression here.



      Another way to do it (not an efficient one) would be using Stream.concat():



      List<Integer> sorted = Stream.concat(
      lucky.stream()
      .filter(elem -> !elem.equals(lucky.get(lucky.size() - 1))).sorted(),
      Stream.of(lucky.get(lucky.size() - 1)))
      .collect(Collectors.toList());


      Note that I am filtering items in the first stream based on value, not the index, as items in lucky list are distinct. This could be done based on the index, though that would make performance of that sorting even worse.






      share|improve this answer























        up vote
        2
        down vote










        up vote
        2
        down vote









        You can use lambda as a second parameter to Collections.sort(), providing sublist as the first parameter:



        Collections.sort(lucky.subList(0, lucky.size()-1), 
        (i1, i2) -> i1.compareTo(i2));


        This will be equivalent to Collections.sort(lucky.subList(0, lucky.size()-1)), so you don't really need this lambda expression here.



        Another way to do it (not an efficient one) would be using Stream.concat():



        List<Integer> sorted = Stream.concat(
        lucky.stream()
        .filter(elem -> !elem.equals(lucky.get(lucky.size() - 1))).sorted(),
        Stream.of(lucky.get(lucky.size() - 1)))
        .collect(Collectors.toList());


        Note that I am filtering items in the first stream based on value, not the index, as items in lucky list are distinct. This could be done based on the index, though that would make performance of that sorting even worse.






        share|improve this answer












        You can use lambda as a second parameter to Collections.sort(), providing sublist as the first parameter:



        Collections.sort(lucky.subList(0, lucky.size()-1), 
        (i1, i2) -> i1.compareTo(i2));


        This will be equivalent to Collections.sort(lucky.subList(0, lucky.size()-1)), so you don't really need this lambda expression here.



        Another way to do it (not an efficient one) would be using Stream.concat():



        List<Integer> sorted = Stream.concat(
        lucky.stream()
        .filter(elem -> !elem.equals(lucky.get(lucky.size() - 1))).sorted(),
        Stream.of(lucky.get(lucky.size() - 1)))
        .collect(Collectors.toList());


        Note that I am filtering items in the first stream based on value, not the index, as items in lucky list are distinct. This could be done based on the index, though that would make performance of that sorting even worse.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 7 at 19:09









        syntagma

        12.3k1247102




        12.3k1247102






























             

            draft saved


            draft discarded



















































             


            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53195505%2fsort-listinteger-using-lambda-expression%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Xamarin.form Move up view when keyboard appear

            Post-Redirect-Get with Spring WebFlux and Thymeleaf

            Anylogic : not able to use stopDelay()