0

first of all sorry for bad english.
Is it possible to split the numbers into half in my array list ? I added each number using .add

public static void main(String[] args) {
    ArrayList<Integer> num = new ArrayList<>();
    num.add(24);
    num.add(18);
    num.add(12);
    num.add(8);
    num.add(20);
    System.out.println(num);
  
    
}          

Output: [24,18,12,8,20]

I want to split it into half like this: [12,12,9,9,6,6,4,4,10,10]

4 Answers4

3

Keeping it simple:

List<Integer> numSplit = new ArrayList<>():
for (Integer n : num) {
    numSplit.add(n / 2);
    numSplit.add(n / 2);
}
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
3

You can also use a Java Stream with the flatMap method:

List<Integer> num = Arrays.asList(24, 18, 12, 8, 20);
List<Integer> splitted = num.stream()
    .flatMap(n -> Stream.of(n/2, n/2))
    .collect(Collectors.toList());
flaxel
  • 4,173
  • 4
  • 17
  • 30
0

This is a simplest approach without any consideration about odd numbers.

public static void main(String[] args) {
    ArrayList<Integer> num = new ArrayList<>();
    num.add(24);
    num.add(18);
    num.add(12);
    num.add(8);
    num.add(20);
    System.out.println(doJob(num));     
}   

private static List<Integer> doJob(List<Integer> lst){
    List<Integer> retval = new ArrayList<>();
    for(Integer a : lst){
        for(int i = 0; i < 2; i++){
            retval.add(a/2);
        }
    }
  return retval;

} 
Renato
  • 2,077
  • 1
  • 11
  • 22
0

There's another fancy stream-based way of splitting with multiplication and division replaced with shifts << and >>:

List<Integer> half2 =IntStream.range(0, num.size() << 1) // create indexes from 0 to 2*n - 1
                              .map(i -> num.get(i>>1)>>1) // get the same element of array for "new" pair of indexes and divide it by 2
                              .boxed()
                              .collect(Collectors.toList());
Nowhere Man
  • 19,170
  • 9
  • 17
  • 42