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.
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:
- Initialize a temporary value with zero.
- Now traverse through the list.
- At each iteration check the temporary value if value equals to odd then return that element otherwise just continue.
- After each iteration increment the temporary value by 1.
- However, this can be done without using temporary value. Since the data in the list is stored using fixed index therefore we can directly check if the index is odd or even and return the element accordingly
**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:
- Traverse the list starting from position 1.
- Now increment the position by 2 after each iteration. By doing this we always end up in an odd position.
- Iteration 1: 1+2=3
- Iteration 2: 2+3=5
- Iteration 3: 5+2=7
- And so on.
- Return the value of the element during each iteration.
**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:
- Create and initialize a list.
- Create a stream of list elements from position 0 to size of the list.
- Use the filter() method to keep only positions that are odd.
- Retrieve the value of the filtered positions.
- Collect the filtered elements into a new list.
- Return the new list.
**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
- Java Program to Print the Elements of an Array Present on Even Position The task is to print all the elements that are present in even position. Consider an example, we have an array of length 6, and we need to display all the elements that are present in 2,4 and 6 positions i.e; at indices 1, 3, 5. Example: Input: [1,2,3,4,5,6] Output: 2 4 6 Input: [1,2] Output: 2 Appr 2 min read
- Java Program to Print the Elements of an Array Present on Odd Position An array stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. In an array, if there are "N" elements, the array iteration starts from 0 and ends with "N-1". The odd positions in the array are those with even indexing and vice versa. E 3 min read
- Java Program to Sort the Elements of an Array in Ascending Order Here, we will sort the array in ascending order to arrange elements from smallest to largest, i.e., ascending order. So the easy solution is that we can use the Array.sort method. We can also sort the array using Bubble sort.1. Using Arrays.sort() MethodIn this example, we will use the Arrays.sort() 2 min read
- Java Program for k-th missing element in sorted array Given an increasing sequence a[], we need to find the K-th missing contiguous element in the increasing sequence which is not present in the sequence. If no k-th missing element is there output -1. Examples : Input : a[] = {2, 3, 5, 9, 10}; k = 1; Output : 1 Explanation: Missing Element in the incre 5 min read
- Java Program to Store Even & Odd Elements of an Array into Separate Arrays Given an array with N numbers and separate those numbers into two arrays by odd numbers or even numbers. The complete operation required O(n) time complexity in the best case. For optimizing the memory uses, the first traverse through an array and calculate the total number of even and odd numbers i 2 min read
- Java Program to Get Elements of a LinkedList Linked List is a linear data structure, in which the elements are not stored at the contiguous memory locations. Here, the task is to get the elements of a LinkedList. 1. We can use get(int variable) method to access an element from a specific index of LinkedList: In the given example, we have used 4 min read
- Find the last element of a Stream in Java Given a stream containing some elements, the task is to get the last element of the Stream in Java.Example:Input: Stream={“Geek_Firstâ€, “Geek_2â€, “Geek_3â€, “Geek_4â€, “Geek_Lastâ€}Output: Geek_LastInput: Stream={1, 2, 3, 4, 5, 6, 7}Output: 7Methods to Find the Last Element of a Stream in JavaThere are 4 min read
- Java Program To Recursively Linearly Search An Element In An Array Given an array arr[] of n elements, write a recursive function to search for a given element x in the given array arr[]. If the element is found, return its index otherwise, return -1.Input/Output Example:Input : arr[] = {25, 60, 18, 3, 10}, Element to be searched x = 3Output : 3 (index )Input : arr 3 min read
- Java Program For Rearranging A Linked List Such That All Even And Odd Positioned Nodes Are Together Rearrange a linked list in such a way that all odd position nodes are together and all even positions node are together, Examples: Input: 1->2->3->4 Output: 1->3->2->4 Input: 10->22->30->43->56->70 Output: 10->30->56->22->43->70Recommended: Please sol 3 min read
- Java Program to Access the Part of List as List A List is an ordered sequence of elements stored together to form a collection. A list can contain duplicate as well as null entries. A list allows us to perform index-based operations, that is additions, deletions, manipulations, and positional access. Java provides an in-built interface <<ja 4 min read