当前位置: 动力学知识库 > 问答 > 编程问答 >

java - How can I split an ArrayList<String> into 2 more ArrayList<String> with a ratio of 1:5

问题描述:

I am trying to split an ArrayList called mainarray into two other ArrayList's

  • ArrayList called array1
  • Arraylist called array2

In the mainarray I have exactly 12 values:

  • "1"
  • "2"
  • "3"
  • ...

How can I split them up so there are 2 random values in array1 and 10 random values in array2

Thank you for your help!

网友答案:

you can use mainarray.size() to find the size of your main ArrayList.

if you want the ratio to be 1:5, there will be 6 total divisions. so use two for loops: one with a range of 1 to size/6, the other with a range of (size/6)+1 to 6*(size/6).

In your example there are 12 elements in your array, so this method will give you 1 and 2 in your array1 and 3 to 12 in your array2.

网友答案:

Just get two random values from one list and add to another.

Random r = new Random();
list1.add(mainarray.remove(r.nextInt(10)));
list1.add(mainarray.remove(r.nextInt(10)));
list2.addAll(mainarray);
网友答案:

Try to use this:
This code select from ArrayList numbers select 2/10 element2 to add at head and add 10 elements at tail:

  public static void main(String[] args) 
  {
   List<Integer> numbers = new ArrayList<Integer>();
   numbers.add(3);
   numbers.add(4);
   numbers.add(5);
   numbers.add(6);
   numbers.add(7);
   numbers.add(55);
   numbers.add(32);
   numbers.add(555);
   numbers.add(1);
   numbers.add(55);

   List<Integer> head = new ArrayList<Integer>();
        List<Integer> tail = new ArrayList<Integer>();
        for(int i = 1; i<=numbers.size(); i++){
            if(i%6==0){
                head.add(numbers.get(i-1));
            }
            else{
                tail.add(numbers.get(i-1));
            }
        }
        System.out.println("head: "+ head); 

        System.out.println("tail: "+tail); 

        System.out.println("numbers: " +numbers); 
     }
分享给朋友:
您可能感兴趣的文章:
随机阅读: