Java Program to Return the Elements at Odd Positions in a List (original) (raw)

Last Updated : 23 Jul, 2024

Given a List, the task is to return the elements at Odd positions in a list. Let's consider the following list.

Odd positions in an array

Clearly, we can see that elements 20, 40, 60 are at Odd Positions as the index of the list is zero-based. Now we should return these elements.

**Approach 1:

**Example:

Java `

// Java Program to Return the Elements // at Odd Positions in a List import java.io.; import java.util.;

class GFG {

public static void main(String[] args)
{
    // Creating our list from above illustration
    List<Integer> my_list = new ArrayList<Integer>();
    my_list.add(10);
    my_list.add(20);
    my_list.add(30);
    my_list.add(40);
    my_list.add(50);
    my_list.add(60);

    // creating a temp_value for checking index
    int temp_val = 0;

    // using a for-each loop to
      // iterate through the list
    System.out.print("Elements at odd position are : ");
    for (Integer numbers : my_list) {
        if (temp_val % 2 != 0) {
            System.out.print(numbers + " ");
        }
        temp_val += 1;
    }
}

}

`

Output

Elements at odd position are : 20 40 60

**Approach 2:

**Example:

Java `

// Java Program to Return the Elements // at Odd Positions in a List

import java.io.; import java.util.;

class GFG {

public static void main(String[] args)
{
    // creating list from above illustration
    List<Integer> my_list = new ArrayList<>();
    my_list.add(10);
    my_list.add(20);
    my_list.add(30);
    my_list.add(40);
    my_list.add(50);
    my_list.add(60);

    // iterating list from position one and incrementing
    // the index value by 2
    System.out.print(
        "Elements at odd positions are : ");
  
    for (int i = 1; i < 6; i = i + 2) {
        System.out.print(my_list.get(i) + " ");
    }
}

}

`

Output

Elements at odd positions are : 20 40 60

Approach 3:

**Example:

Java `

// Java Program to Return the Elements // at Odd Positions in a List import java.util.; import java.util.stream.;

public class GFG { public static void main(String[] args) { // Creating our list List my_list = Arrays.asList(10, 20, 30, 40, 50, 60); // filtering out odd position elements List oddPosList = IntStream.range(0, my_list.size()) .filter(numbers -> numbers % 2 != 0) .mapToObj(my_list::get) .collect(Collectors.toList()); // printing the filtered elements System.out.println("Elements at odd position are : " + oddPosList); } }

`

Output

Elements at odd position are : [20, 40, 60]

Similar Reads