0

I want to display only 12 sorted elements from myList. If the size is less than 12, say 5, or 3, or 1, still I need to loop and display only those available items.

Below is my code:

public class JavaApplication {

    public static void main(String[] args) {

        List<String> myList = new ArrayList<>();
        myList.add("20150830");
        myList.add("20141201");
        myList.add("20150716");
        myList.add("20151131"); 
        myList.add("20141101");
        myList.add("20150620");
        myList.add("20150301");
        myList.add("20150702");
        myList.add("20150511");

        Collections.sort(myList,Collections.reverseOrder());

        for(int i = 0; i < myList.size(); i++) {
            System.out.println(myList.get(i).toString());
        }
    }     
}
5
  • 4
    Try: for(int i = 0; i < myList.size() && i < 12; i++){ Commented Aug 12, 2015 at 9:19
  • 4
    Alternatively for(int i = 0; i < Math.min(myList.size(),12); i++){ Commented Aug 12, 2015 at 9:20
  • use list.sublist(from,to) Commented Aug 12, 2015 at 9:33
  • If there is more than 12 elements, should the first 12 still be printed? Commented Aug 12, 2015 at 9:39
  • possible duplicate of Ways to iterate over a List in java? Commented Aug 12, 2015 at 9:48

6 Answers 6

2

This is a good use-case for streams.

myList.stream()
        .sorted(Comparator.<String>reverseOrder())
        .limit(12)
        .forEach(System.out::println);
Sign up to request clarification or add additional context in comments.

Comments

2

Just add one more condition in your loop to restrict the loop for 12.

for(int i = 0; i < myList.size() &&  i < 12 ; i++){
    System.out.println(myList.get(i).toString());
}

Comments

1

You can try:

int maxValuesToDisplay=12;
int maxToIterate=(myList.size()<maxValuesToDisplay) ? myList.size() : maxValuesToDisplay;

for(int i = 0; i < maxToIterate; i++){
    System.out.println(myList.get(i).toString());
}

1 Comment

Well, Math.min looks much better then this ternary operator :P.
0

Use List.subList(int fromIndex, int toIndex);

public class JavaApplication {

    public static void main(String[] args) {

        List<String> myList = new ArrayList<>();
        myList.add("20150830");
        myList.add("20141201");
        myList.add("20150716");
        myList.add("20151131"); 
        myList.add("20141101");
        myList.add("20150620");
        myList.add("20150301");
        myList.add("20150702");
        myList.add("20150511");


        Collections.sort(myList,Collections.reverseOrder());
        int a = myList.size();
        List subList = null;
        if(a<12)
        subList = myList.subList(0,a);
        else subList = myList.subList(0,12);
       //Print sublist now 

 }     
    }

2 Comments

Combine this with Math.min() would be much cleaner: List subList = myList.subList(0, Math.min(myList.size(), 12)), all in 1 line, not 5
@MarkFisher True Mark :)
0

You could use the Math.min() function and iterate the minimum of 12 and the list-size.

for(int i = 0; i < Math.min(myList.size(), 12); i++){
    System.out.println(myList.get(i).toString());
   }

4 Comments

This is not optimal as this compute the min on each loop.
list.size() is O(1) (see stackoverflow.com/questions/6540511/…) and Math.min(num, num) is hardly going to add any significant overhead.
Also Math.min() is same as the < operator, has no complexity. Have a look at this. ThIs keeps the for statement clean.
Except this is an object oriented language and you don't know what is behind "size()". Anyway for optimization, always get out of the loops invariants you can compute.
0

You can use TreeSet :

public static void main(String[] args) {
    Set<String> myList = new TreeSet<>();
    myList.add("20150830");
    myList.add("20141201");
    myList.add("20150716");
    myList.add("20151131");
    myList.add("20141101");
    myList.add("20150620");
    myList.add("20150301");
    myList.add("20150702");
    myList.add("20150511");

    int i = 0;
    for(String s : myList){
        System.out.println(s);
        i++;
        if(i >= 5) {
            break;
        }
    }
}

And for reverse order :

    public static void main(String[] args) {
        TreeSet<String> myList = new TreeSet<>();
        myList.add("20150830");
        myList.add("20141201");
        myList.add("20150716");
        myList.add("20151131");
        myList.add("20141101");
        myList.add("20150620");
        myList.add("20150301");
        myList.add("20150702");
        myList.add("20150511");

        Iterator<String> it = myList.descendingIterator();
        int i = 0;

        while(it.hasNext()) {
            String s = it.next();
            System.out.println(s);
            i++;
            if (i >= 5) {
                break;
            }
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.