***************coding Interview Questions Programs***************
=====================================================================
package [Link];
import [Link];
public class AnagramCheckerWithStreamapi {
public static void main(String[] args) {
String str1 = "Listen";
String str2 = "silent";
boolean isAnagram =[Link]([Link]()
.chars().sorted().toArray(), [Link]()
.chars().sorted().toArray());
[Link](isAnagram ? "Anagrams" : "Not Anagrams");
}
}
=========================
package [Link];
import [Link];
public class AnagramCheckEx2 {
public static void main(String[] args) {
String str1 = "Listen";
String str2 = "silent";
// Convert strings to char arrays and sort them
char[] arr1 = [Link]().toCharArray();
char[] arr2 = [Link]().toCharArray();
[Link](arr1);
[Link](arr2);
// Compare the sorted arrays
if ([Link](arr1, arr2)) {
[Link](str1 + " and " + str2 + " are anagrams.");
} else {
[Link](str1 + " and " + str2 + " are not anagrams.");
}
}
}
===================================
package [Link];
public class Armstrong {
public static void main(String[] args) {
if ([Link] == 0) {
[Link]("Please provide a valid input.");
return;
}
int num = [Link](args[0]);
int sum = 0, temp = num, digits = [Link](num).length();
while (temp > 0) {
sum += [Link](temp % 10, digits);
temp /= 10;
}
[Link](sum == num ? num + " is Armstrong" : num + " is not
Armstrong");
}
}
================================
package [Link];
import [Link];
public class ArrayEqualityChecker {
public static void main(String[] args) {
int[] array1 = {1, 2, 3, 4, 5};
int[] array2 = {1, 2, 3, 4, 5};
int[] array3 = {1, 2, 3, 4, 6};
// Check if two arrays are equal
boolean result1 = [Link](array1, array2); // Should return true
boolean result2 = [Link](array1, array3); // Should return false
[Link]("array1 and array2 are equal: " + result1);
[Link]("array1 and array3 are equal: " + result2);
}
}
================================
package [Link];
import [Link].*;
import [Link];
import [Link];
public class CharacterCountWithStreams {
public static void main(String[] args) {
String str1 = "abcdABCDabcd";
Map<Character, Long> charsCount = [Link]()
.mapToObj(c -> (char) c) // Convert int stream to Character stream
.collect([Link]([Link](),
[Link]())); // Count each character
[Link](charsCount); // Output: {a=2, A=1, b=2, B=1, c=2, C=1,
d=2, D=1}
}
}
============================
package [Link];
public class CharacterPyramid {
public static void main(String[] args) {
char ch = 'A'; // Starting character
int rows = 5; // Number of rows
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= rows - i; j++) {
[Link](" "); // Print spaces
}
for (int k = 1; k <= (2 * i - 1); k++) {
[Link](ch); // Print the character
}
[Link]();
ch++; // Move to the next character
}
}
}
===================================
package [Link];
public class CheckOnlyDigitsInString {
public static void main(String[] args) {
String input = "123456"; // Example string
// Check if the string contains only digits using regex
if ([Link]("[0-9]+")) {
[Link]("The string contains only digits.");
} else {
[Link]("The string does not contain only digits.");
}
}
}
=======================================
package [Link];
import [Link];
import [Link];
public class Count_OddandEven_Numbers {
public static void main(String[] args) {
int[] a = {1, 2, 3, 4, 5, 6};
int evencount = 0;
int oddcount = 0;
List<Integer> evenNumbers = new ArrayList<>();
List<Integer> oddNumbers = new ArrayList<>();
for (int bs : a) {
if (bs % 2 == 0) { // Correct condition
evencount++;
[Link](bs);
} else {
oddcount++;
[Link](bs);
}
}
// Final counts and numbers
[Link]("Total even numbers: " + evencount);
[Link]("Even numbers: " + evenNumbers);
[Link]("Total odd numbers: " + oddcount);
[Link]("Odd numbers: " + oddNumbers);
}
}
=====================================
package [Link];
import [Link];
public class countingOddNumbers {
public static void main(String[] args) {
int [] array = {1,2,3,4,5,6,7,8,9,10};
// for(int num : array){
// if(num%2 !=0){
// [Link]("odd numbers are :"+ num);
// }
// }
// using streamapi
// [Link](array).filter(num->num%2!=0).forEach(num->
[Link]("odd num is "+num));
//using count method
long count = [Link](array)
.filter(num->num%2!=0)
.peek(num-> [Link]("odd num is "+num))
.count();
[Link]("total number os odd numbers is :"+ count);
}
}
=======================================
package [Link];
public class CountSpecificLetterInString {
public static void main(String[] args) {
String s = "india is a country";
// Using Java 8 Streams to count occurrences of 'i'
long countno = [Link]() // Convert string to IntStream
.filter(c -> c == 'i') // Filter the characters where 'i' is
present
.count(); // Count the occurrences
[Link]("Number of occurrences of 'i': " + countno);
}
}
=====================================
package [Link];
public class CountSumofDigits {
public static void main(String[] args) {
int n = 01234567;
int sum = 0;
while(n>0){
sum += n%10;
n = n/10;
sum++;
}
[Link]("Total digits sum is : "+sum);
}
}
===================================
package [Link];
public class CountTotalDigits {
public static void main(String[] args) {
int n = 123455679;
int count = 0;
while(n>0){
n = n/10;
count++;
}
[Link]("total digits in number are : "+count);
}
}
====================================
package [Link];
public class DuckNumber {
public static void main(String[] args) {
int num = 101;
[Link](num + " is " + (isDuckNumber(num) ? "a Duck number" :
"not a Duck number"));
}
public static boolean isDuckNumber(int num) {
String numStr = [Link](num);
return [Link](0) != '0' && [Link]("0");
}
}
======================
package [Link];
import [Link];
import [Link];
public class DuplicateElimentinArray {
public static void main(String[] args) {
//approach 1
String [] arr = {"java","c++","python","java","mongodb"};
// HashSet<String> hs = new HashSet<>();
// for(String a : arr){
// if([Link](a)== false){
// [Link]("Duplicate eliment is :"+ a);
// }
//
// }
//approach 2
HashMap<String,Integer> hs = new HashMap<>();
for(String b : arr){
[Link](b,[Link](b,0)+1);
}
for([Link]<String,Integer> entry : [Link]()){
if([Link]()>1){
[Link]("duplicate key is :"+ [Link]());
}
}
}
}
===========================================
package [Link];
import [Link].*;
import [Link];
public class DuplicateLettersRemove {
public static void main(String[] args) {
String[] s = {"Bananas", "Apple", "tomato"};
for (String word : s) {
// Using LinkedHashSet to preserve order and remove duplicates
String result = new LinkedHashSet<>([Link]([Link]("")))
.stream()
.collect([Link]());
[Link](result);
}
}
}
===================================
package [Link];
import [Link];
import [Link];
import [Link];
public class EmployeesSortedDescendingbyName {
public static void main(String[] args) {
ArrayList<Employees> emplist = new ArrayList<>();
[Link](new Employees("Naresh",1,"Development",30000));
[Link](new Employees("Rajesh",2,"Safety",28000));
[Link](new Employees("Karna",3,"Development",31000));
[Link](new Employees("Fiona",4,"Testing",28000));
//Descending order
// [Link]((e1,e2)->[Link]().compareTo([Link]()));
// for Ascending oreder
// [Link]((e1,e2)->[Link]().compareTo([Link]()));
// Define a Comparator for natural sorting by name
// Comparator<Employees> nameComparator =
[Link](Employees::getName);
// Define a Comparator for customized sorting or Descending order by name
Comparator<Employees> nameComparatorDesc =
[Link](Employees::getName).reversed();
// Sort the list using the Comparator
[Link](nameComparatorDesc);
// [Link]([Link]::println);
// Skip the first 2 names and print the 3rd one
[Link]()
.skip(2) // Skip the first 2 names
.findFirst() // Get the 3rd name (after skipping 2)
.ifPresent([Link]::println); // Print the 3rd name
}
}
=====================================
package [Link];
import [Link];
import [Link];
public class ExtractSpacesFromCharArrayExample {
public static void main(String[] args) {
char[] a = {'a', ' ', 'b', ' ', 'c', ' '};
// Create separate lists for spaces and non-spaces
List<Character> nonSpaces = new ArrayList<>();
List<Character> spaces = new ArrayList<>();
// Loop through the char array and add characters to the respective lists
for (char ch : a) {
if (ch == ' ') {
[Link](ch); // Add spaces to the spaces list
} else {
[Link](ch); // Add non-space characters to nonSpaces list
}
}
List<Character> result = new ArrayList<>(spaces); // Create a new list with
Spaces
[Link](nonSpaces); // Add Nonspaces to the list
// Print the concatenated result
[Link](result);
}
}
=============================================
package [Link];
import [Link];
import [Link];
import [Link];
public class ExtractZerosFromarray {
public static void main(String[] args) {
int [] a = {1,3,0,4,3,0,0,7};
//concating zeros first and numbers
int [] x = [Link](
[Link](a).filter(n->n==0),
[Link](a).filter(n->n!=0)).toArray();
[Link]([Link](x));
}
}
====================================
package [Link];
import [Link];
import [Link];
public class ExtractZerosFromArrayEx2 {
public static void main(String[] args) {
int[] a = {1, 3, 0, 4, 3, 0, 0, 7};
// Extracting zeros
int[] zeros = [Link](a).filter(n -> n == 0).toArray();
// Extracting non-zero numbers
int[] nonZeros = [Link](a).filter(n -> n != 0).toArray();
// Print extracted zeros and remaining numbers separately
[Link]("Extracted zeros: " + [Link](zeros));
[Link]("Remaining numbers: " + [Link](nonZeros));
}
}
=====================================
package [Link];
import [Link];
import [Link];
public class ExtractZerosFromStringArray {
public static void main(String[] args) {
String[] a = {"apple", "", "banana", "", "orange", ""};
// Concatenate empty strings first, then the rest of the strings
String[] result = [Link](
[Link](a).filter(s -> [Link]()), // filter empty strings
[Link](a).filter(s -> ![Link]())) // filter non-empty
strings
.toArray(String[]::new); // Convert to array
[Link]([Link](result));
}
}
=================================
package [Link];
import [Link];
public class FibonacciSeries {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Please provide number to generate Fibonacci series");
int n = [Link]();
int first = 0, second =1;
[Link]("fibonacci series : ");
for(int i = 0;i <n;i++){
[Link](first+" ");
int next = first+second;
first = second;
second = next;
}
}
}
====================================
package [Link];
import [Link];
import [Link];
public class FindFrequencyExample {
public static void main(String[] args) {
if ([Link] == 0) {
[Link]("Please provide a string as input.");
return;
}
// Input string
String str = [Link](" ", args).toLowerCase();
// Create a HashMap to store character frequencies
Map<Character, Integer> freqMap = new HashMap<>();
// Iterate through the string
for (char ch : [Link]()) {
if (ch != ' ') { // Ignore spaces
[Link](ch, [Link](ch, 0) + 1);
}
}
// Print the character frequencies in the desired format
[Link]((key, value) -> [Link](key + "" + value + " "));
}
}
=================================
package [Link];
import [Link];
import [Link];
public class FindLargestAndSmallestNumbers {
public static void main(String[] args) {
int [] a = {2,3,5,67,98,123,-5555};
var small = [Link](a).min().getAsInt();
var large = [Link](a).max().getAsInt();
[Link]("min and max numbers are %d & %d%n ",small,large);
}
}
=====================================
package [Link];
public class FindMissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 4,5, 6,7};
int sum1 = 0;
for(int b : arr){
sum1 = sum1+b;
}
// for (int i = 0; i < [Link]; i++) {
// sum1 = sum1 + arr[i];
// }
[Link]("sum of elements in array:" + sum1);
int sum2 =0;
for(int j=1; j<=7; j++){
sum2 = sum2+j;
}
[Link]("sum of elements in array2 :"+sum2);
// int missingnum = sum2-sum1;
[Link]("missing number is "+ (sum2-sum1));
}
}
=====================================
package [Link];
import [Link];
import [Link];
public class FindNonRepeatingThirdCharacterExample {
public static void main(String[] args) {
if ([Link] == 0) {
[Link]("Please provide a string as input.");
return;
}
// Input string
// String str = [Link](" ", args).toLowerCase();
String str = args[0];
// Create a HashMap to store character frequencies
Map<Character, Integer> freqMap = new HashMap<>();
// Populate the frequency map
for (char ch : [Link]()) {
if (ch != ' ') { // Ignore spaces
[Link](ch, [Link](ch, 0) + 1);
}
}
// Find the 3rd non-repeating character
int count = 0;
for (char ch : [Link]()) {
if (ch != ' ' && [Link](ch) == 1) { // Check if the character is
non-repeating
count++;
if (count == 3) {
[Link]("The 3rd non-repeating character is: " +
ch);
return;
}
}
}
[Link]("There is no 3rd non-repeating character in the input
string.");
}
}
=============================
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class GetAnameFromList {
public static void main(String[] args) {
List<String> l = new
ArrayList<>([Link]("Sam","Ram","Karan","Naresh","Giri","Raja","Kumar","Ashok
","Newton"));
List<String> result = [Link]().filter(n-
>[Link]("A")).collect([Link]());
[Link](result);
/**
* Count a in the collection
*/
Long count = [Link]().filter(n->[Link]("N")).count();
[Link](count);
}
}
=================================
package [Link];
import [Link].*;
import [Link];
public class GetValuesOnlyFromMap {
public static void main(String[] args) {
Map<Integer, String> ma = new HashMap<>();
[Link](1, "Naresh");
[Link](2, "Mahesh");
[Link](3, "Krishna");
[Link](4, "AdinathGiri");
[Link](5, "Ashok");
[Link](6, "Surya");
// approach-1
// Collection<String> cl = [Link]();
// [Link](cl);
// Using stream() and collecting the values
// List<String> values = [Link]().stream().collect([Link]());
// [Link](values);
//normal approach
for([Link]<Integer,String> mdta : [Link]() ){
var value = [Link]();
[Link](value);
}
}
}
=============================
package [Link];// Java Code to check if two Strings are anagrams of
// each other using sorting
import [Link];
class GfG {
// Function to check if two strings are anagrams
static boolean areAnagrams(String s1, String s2) {
// Sort both strings
char[] s1Array = [Link]();
char[] s2Array = [Link]();
[Link](s1Array);
[Link](s2Array);
// Compare sorted strings
return [Link](s1Array, s2Array);
}
public static void main(String[] args) {
String s1 = "geeks";
String s2 = "kseeg";
[Link](areAnagrams(s1, s2));
}
}
===================================
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class Groupbydept {
public static ArrayList<Employee> employeedata() {
ArrayList<Employee> ee = new ArrayList<>();
[Link](new Employee(1, "HR", 12000));
[Link](new Employee(2, "SALES", 10000));
[Link](new Employee(3, "ACCOUNTS", 10000));
[Link](new Employee(4, "QC", 12500));
[Link](new Employee(5, "SAFETY", 8000));
return ee;
}
public static void main(String[] args) {
var employeedata = employeedata();
[Link]("Employee Data: " + employeedata);
var collect =
[Link]().collect([Link](Employee::getDepartment,
[Link](Employee::getSalary)));
[Link]((department, salaryMap) -> {
[Link]("Department: " + department);
[Link]((salary, employees) -> {
[Link](" Salary: " + salary);
[Link]([Link]::println);
});
});
}
}
======================================
package [Link];
import [Link];
import [Link];
import [Link];
public class HalfLinkedListReverseWithInteger {
public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
[Link](1);
[Link](10);
[Link](100);
[Link](1000);
[Link](20);
[Link](21);
[Link](1,34);
[Link](list);
// Calculate the midpoint
int midpoint = [Link]()/2;
// Create a ListIterator starting from the midpoint
ListIterator<Integer> iterator = [Link](midpoint);
// Iterate in reverse order for the first half
for (int i = 0; i < midpoint; i++) {
if ([Link]()) {
[Link]([Link]());
}
}
Integer [] sechalf = new Integer[[Link]() - midpoint];
// Iterate in reverse order for the second half (after the midpoint)
// First, find the midpoint for the second half, then reverse iterate
int index =0;
for (int i = [Link]() - 1; i >= midpoint; i--) {
sechalf[index] = [Link](i); // Store the element in the array
index++;
}
[Link]("Second half in reverse: " + [Link](sechalf));
}
}
====================================
package [Link];
import [Link].*;
public class HalfLinkedListReverseWithString {
public static void main(String[] args) {
// Creating and populating the LinkedList
LinkedList<String> list = new LinkedList<>();
[Link]("Naresh");
[Link]("Narasimha");
[Link]("Frances");
[Link]("John");
[Link]("Suman");
[Link]("Dinesh");
[Link]("Raja");
[Link]("Original Linked List: " + list);
// Find the midpoint of the list
int midpoint = [Link]() / 2;
// First half of the list (to be reversed)
List<String> firstHalf = new ArrayList<>([Link](0, midpoint));
[Link](firstHalf);
// Second half of the list (to be reversed)
List<String> secondHalf = new ArrayList<>([Link](midpoint,
[Link]()));
[Link](secondHalf);
// Print the reversed first half and second half
[Link]("Reversed first half of Linked List: " + firstHalf);
[Link]("Reversed second half of Linked List: " + secondHalf);
}
}
===================================
package [Link];
import [Link];
public class Leapyearchecker {
public static void main(String[] args) {
var i = [Link](args[0]);
Year y = [Link](i);
if([Link]()){
[Link](y+" is leap year");
}
else {
[Link](y + " not a leap year");
}
}
}
===================================
package [Link];
import [Link].*;
public class MaxNumberFind {
public static void main(String[] args) {
// Create a list of integers
List<Integer> l = [Link](12, 34, 56, 6, 9, 45, 2344, 90, 45);
// Use [Link]() to find the maximum number
int max = [Link](l);
// Print the maximum number
[Link]("Max Number: " + max);
}
}
====================================
package [Link];
import [Link];
public class MaxNumberFindByTakingValuesFromScanner {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Read the size of the array
[Link]("Enter the size of the array: ");
int size = [Link]();
// Create an array of the given size
int[] numbers = new int[size];
// Read array elements from the user
[Link]("Enter the numbers:");
for (int i = 0; i < size; i++) {
numbers[i] = [Link]();
}
// Find the maximum number manually
int max = numbers[0]; // Start by assuming the first element is the maximum
for (int num : numbers) {
if (num > max) {
max = num;
}
}
// Print the maximum number
[Link]("Max Number: " + max);
[Link]();
}
}
========================================
package [Link];
import [Link].*;
public class MaxNumberFindWithOutCollectionsMax {
public static void main(String[] args) {
// Create a list of integers
List<Integer> l = [Link](12, 34, 56, 6, 9, 45, 2348, 9000, 45);
// Initialize max with the first element
int max = [Link](0);
// Iterate through the list to find the maximum number
for (int num : l) {
if (num > max) {
max = num;
}
}
// Print the maximum number
[Link]("Max Number: " + max);
}
}
====================================
package [Link];
import [Link];
public class MaxTwoFinder {
public static void main(String[] args) {
int[] v = {3, 546, 66, 774, 2, 1, 0};
// Sort the array in ascending order
[Link](v);
// Print the largest and second largest numbers (after sorting, they will
be the last two elements)
int max1 = v[[Link] - 1]; // Largest number
int max2 = v[[Link] - 2]; // Second largest number
[Link]("The two largest numbers are: " + max1 + " and " +
max2);
}
}
=============================
package [Link];
import [Link].*;
public class MaxTwoNumbersUsingCollectionsReverse {
public static void main(String[] args) {
// Create a list of integers
List<Integer> numbers = [Link](12, 34, 56, 6, 9, 45, 24, 90, 45);
// Sort the list in descending order
[Link]([Link]());
// Get the two largest numbers
int max1 = [Link](0);
int max2 = [Link](1);
// Print the two largest numbers
[Link]("The two largest numbers are %d and %d%n", max1, max2);
}
}
=======================================
package [Link];
import [Link];
import [Link];
import [Link];
public class MergeTwoLists {
public static void main(String[] args) {
List<Integer> l1 = new ArrayList<>();
[Link](1);
[Link](2);
[Link](3);
List<Integer> l2 = new ArrayList<>();
[Link](4);
[Link](5);
[Link](6);
//approach -1
// List<Integer> l3 = new ArrayList<>(l1);
// [Link](l2);
// [Link](l3);
// Use flatMap by converting each list into a stream and then flattening
them
[Link](l1, l2)
.flatMap(List::stream) // Flatten both lists into a single stream
.forEach([Link]::println); // Print each element
}
}
============================================
package [Link];
import [Link].*;
public class MiddleWordChecker {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("Please provide the input string or Number:");
String input = [Link]();
[Link]("Please provide the input to find:");
String wordtofind = [Link]();
// Check if the word is larger than the input
if ([Link]() > [Link]()) {
[Link]("The input to find is larger than the input.");
return;
}
// Calculate the starting index of the middle substring
int midstart = ([Link]() - [Link]()) / 2;
// Check if the word is present in the middle
if ([Link](midstart, midstart +
[Link]()).equals(wordtofind)) {
[Link]("The input to find is present in the middle of the
input: " + wordtofind);
} else {
[Link]("The input to find is not present in the middle of
the input: " + wordtofind);
}
}
}
======================================
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class MultipleByFiveUsingStreams {
public static void main(String[] args) {
int c = [Link](args[0]);
List<Integer> al = [Link](1,2,3,4,5,6,7,8,9,10);
List<Integer> result = [Link]().map(n-
>n*c).collect([Link]());
[Link](result);
}
}
==========================================
package [Link];
//import [Link].*;
public class PalindromeCheck {
public static void main(String[] args) {
String str = "madam";
boolean isPalindrome = [Link](
new StringBuilder(str).reverse().toString());
[Link](isPalindrome ? "Palindrome" : "Not Palindrome");
}
}
========================================
package [Link];
import [Link];
public class PalindromeStringCheck {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
[Link]("enter input to check palindrome");
String input = [Link]();
int inputlength = [Link]();
String rev = "";
for(int i = inputlength-1;i>=0;i--){
rev += [Link](i);
}
if([Link]().equals([Link]())){
[Link]("given input is palindrome "+ input);
}
else{
[Link]("given input is not palindrome "+ input);
}
}
}
===================================
package [Link];
public class PrimeChecker {
public static void main(String[] args) {
int num = [Link](args[0]);
if (num > 1 && isPrime(num)) {
[Link](num + " is a prime number.");
} else {
[Link](num + " is not a prime number.");
}
}
public static boolean isPrime(int num) {
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) return false;
}
return true;
}
}
==================================
package [Link];
import [Link];
public class PrimeCheckerWithStreams {
public static void main(String[] args) {
int num = [Link](args[0]);
// Check if the number is prime using IntStream and a lambda expression
[Link](num + (num > 1 && [Link](2, (int)
[Link](num) + 1)
.noneMatch(i -> num % i == 0) ? " is a prime number." : " is not a
prime number."));
}
}
=================================
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class RemoveDuplicatesfromListwithoutSetormap {
public static void main(String[] args) {
List<Integer> l = [Link](1,2,2,2,3,4,5,6,3,4,8,9,12,34,5);
List<Integer> x = [Link]().distinct().collect([Link]());
[Link](x);
}
}
==========================
package [Link];
import [Link];
import [Link];
public class RemoveDuplicateWithoutdistinctsetandmap {
public static void main(String[] args) {
List<Integer> l = new ArrayList<>();
[Link](1);
[Link](1);
[Link](2);
[Link](3);
[Link](2);
[Link](4);
[Link](3);
removeduplicates((ArrayList<Integer>) l);
[Link]("unique elements in list is "+l);
}
public static void removeduplicates(ArrayList<Integer> l){
ArrayList<Integer> al = new ArrayList<>();
for(Integer num :l){
if(){
[Link](num);
}
}
[Link]();
[Link](al);
}
}
===========================================
package [Link];
public class RemoveOccurancesofChars {
public static void main(String[] args) {
String str = "abadefaghi";
str = [Link]("a","");
[Link](str);
}
}
===========================
package [Link];
public class ReverseaNumber {
public static void main(String[] args) {
int n = 123456;
String res = new StringBuilder([Link](n)).reverse().toString();
[Link](res);
// StringBuilder sbl = new StringBuilder();
// [Link](n);
// [Link]();
// [Link](sbl);
// int n = 987654;
// StringBuffer sb = new StringBuffer([Link](n));
// [Link]([Link]());
// int rev =0;
// while (n!=0){
// rev = rev*10+n%10;
// n = n/10;
// [Link]("Reverse Number is "+rev);
// }
}
}
================================
package [Link];
public class ReverseaString {
public static void main(String[] args) {
String s = "naresh";
// StringBuffer sb = new StringBuffer(s);
// [Link]([Link]());
// StringBuilder sbl = new StringBuilder(s);
// [Link]([Link]());
String rev = "";
int length = [Link]();
for(int i = length-1;i>=0;i--){
rev = rev +[Link](i);
[Link](rev);
}
}
}
=========================
package [Link];
import [Link];
public class ReverseLinkedList {
public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<>();
[Link](1);
[Link](2);
[Link](3);
[Link]("original order is : "+ll);
LinkedList<Integer> ll1 = new LinkedList<>();
[Link]().forEachRemaining(ll1::add);
[Link]("reverse Order : "+ll1);
}
}
================================
package [Link];
import [Link].*;
public class ReverseLinkedListWithCollection {
public static void main(String[] args) {
LinkedList<Integer> ll = new LinkedList<>([Link](1, 2, 3));
[Link]("Original order: " + ll);
// Reverse the LinkedList using [Link]
[Link](ll);
[Link]("Reversed order: " + ll);
}
}
===================================
package [Link];
import [Link].*;
public class ReverseStringbyGivenInputLength {
public static void main(String[] args) {
String s = "knowledge is power try to improve it";
int strlength = [Link]();
Scanner sc = new Scanner([Link]);
// Request user input
[Link]("Please provide the input number to reverse the String
from:");
int num = [Link]();
// Check if the input number is within valid range
if (num <= strlength && num >= 0) {
// Reverse the substring from index 'num' to the end of the string
StringBuilder sb = new StringBuilder([Link](num)).reverse();
// Append the first part of the string unchanged
[Link](0, [Link](0, num));
// Print the result
[Link]("Modified String: " + sb);
} else {
[Link]("Entered number input is larger than the string
length or invalid.");
}
// Close the scanner object
[Link]();
}
}
===============================
package [Link];
import [Link];
public class ReverseStringByGivenLength {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter a string: ");
String inputString = [Link]();
[Link]("Enter number to reverse the string from the given input
length: ");
int len = [Link]();
if (len <= [Link]())
// [Link]("Reversed String: " + new
StringBuilder([Link](0, len)).reverse() +
[Link](len));
[Link]("Reversed String: " + [Link](0, len)
+ new StringBuilder([Link](len)).reverse());
else
[Link]("Error: Length exceeds string length.");
[Link]();
}
}
============================
package [Link];
import [Link];
public class ReverseStringbyPreservingSpaces {
public static void main(String[] args) {
if ([Link] == 0) {
[Link]("Please provide an input string.");
return;
}
// Combine all input arguments into a single string
String str = [Link](" ", args);
// Create a character array from the string
char[] result = [Link]();
// Remove spaces and reverse the string
String reversedWithoutSpaces = new StringBuilder([Link](" ",
"")).reverse().toString();
int index = 0; // Pointer for characters in the reversed string
for (int i = 0; i < [Link]; i++) {
if (result[i] != ' ') { // Replace only non-space characters
result[i] = [Link](index++);
}
}
// Print the final reversed string with spaces preserved
// [Link](new String(result));
[Link]([Link](result));
}
}
==================================
package [Link];
import [Link];
public class SearchForElement {
public static void main(String[] args) {
int n = 1234567;
[Link]("input number is : "+n);
[Link]("Enter number to search in the input vnumber : ");
Scanner sc = new Scanner([Link]);
int searchno = [Link]();
[Link]((n+"").contains(searchno+ "")?"Search Element found":
"Search Element not found");
}
}
=================================
package [Link];
import [Link];
import [Link];
import [Link];
public class SecondLargeNumFromRandomNumbers {
public static void main(String[] args) {
List<Integer> al = [Link](2,34,45,7,8,12,1,123,7,3,235);
// [Link](al,[Link]());
// [Link]([Link](1));
// approach-2
var slarge = [Link]().sorted((a,b)->b-
a).skip(1).findFirst().orElseThrow();
[Link](slarge);
}
}
==================================
package [Link];
import [Link].*;
public class SortHashMapByValue {
public static void main(String[] args) {
// Creating a HashMap
HashMap<String, Integer> map = new HashMap<>();
[Link]("One", 1);
[Link]("Four", 4);
[Link]("Three", 3);
[Link]("Two", 2);
// Sorting by values
[Link]().stream()
.sorted([Link]()) // Sort by values
.forEach(entry -> [Link]([Link]() + " = " +
[Link]()));
}
}
===================================
package [Link];
import [Link];
import [Link];
import [Link];
public class SquareTheNumbers {
public static void main(String[] args) {
List<Integer> list = [Link](1,2,3,4,5);
// [Link]().map(n->n*n).forEach([Link]::println);
var collect = [Link]().map(n -> n * n).collect([Link]());
[Link](collect);
}
}
======================================
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class StreamapiMapExample{
public static void main(String[] args) {
List<Integer> list = [Link](809,90,112,134,234);
// int max = [Link](list);
// [Link](max);
int max = [Link]().max(Integer::compareTo).orElseThrow();
[Link](max);
// Optional<Integer> maax = [Link]().filter(n->n>100)
// .max(Integer::compareTo);
// [Link]([Link]::println);
}
}
=================================
package [Link];
public class StringImmutabilityExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = str1; // str2 points to the same object as str1
// Attempt to modify str1
str1 = str1 + " World";
// Print both strings
[Link]("str1: " + str1); // str1 is modified to "Hello World"
[Link]("str2: " + str2); // str2 remains "Hello"
}
}
================================
package [Link];
public class StringValuesSameContent {
public static void main(String[] args) {
String emp1 = "Radha";
String emp2 = "Naresh";
String emp3 =emp1;
[Link]( emp3==emp1);
[Link]([Link](emp1));
}
}
==================================
package [Link];
public class SwappingArrayElements {
public static void main(String[] args) {
String [][] x = {{"A","B"},{"C","D"}};
for (int i=[Link]-1;i>=0;i--){
for(int j=0;j<x[i].length;j++){
[Link](x[i][j]);
}
}
}
}
O/P :: CDAB
=================================
package [Link];
public class SwappingArrayindexvalues {
public static void main(String[] args) {
String [][] s = {{"A","B"},{"C","D"}};
for(int i=0;i<[Link];i++){
for(int j=s[i].length-1;j>=0;j--){
[Link](s[i][j]);
}
}
}
O/P :: BADC
======================================
package [Link];
public class SwappingTwoNumbers {
public static void main(String[] args) {
int a = 10;
int b = 20;
// int t =a;
// a=b;
// b=t;
// [Link](a+" "+b);
// a= a+b;
// b =a-b;
// a = a-b;
// [Link](a+" "+b);
// a= a*b;
// b =a/b;
// a = a/b;
// [Link](a+" "+b);
a= a^b;
b= a^b;
a= a^b;
[Link](a+ " "+b);
// b =a+b -(a=b);
// [Link](a+" "+b);
}
}
=====================
package [Link];
public class SwappingTwoStringsWithOutThirdVariable {
public static void main(String[] args) {
String s1 = "abc";
String s2 = "def";
s1 = [Link](s2);
s2 = [Link](0,[Link]()-[Link]());
s1 = [Link]([Link]());
[Link](s1+ ":"+s2);
}
}
================================
package [Link];
import [Link];
import [Link];
public class TotallingallthevaluesinaList {
public static void main(String[] args) {
List<Integer> list = [Link](2,4,5,7,88,90);
int sum = [Link]().mapToInt(n->n).sum();
[Link](sum);
}
}
===========================
package [Link];
import [Link];
import [Link];
public class TwoMaxElementsFinder {
public static void main(String[] args) {
Integer[] c = {132, 399, 5, 767, 70};
//approach-1
// [Link](c, [Link]());
// [Link](c[0]);
// [Link](c[1]);
//approach-2
// Directly sort the array in descending order and take the first two
elements
int[] maxTwo = [Link](c)
.sorted((a, b) -> b - a) // Sort descending
.mapToInt(Integer::intValue) // Convert back to int
.toArray(); // Collect as an array
// [Link]("The two largest numbers are: " + maxTwo[0] + " and "
+ maxTwo[1]);
[Link]("the two largest numbers are %d & %d%n",
maxTwo[0],maxTwo[1]);
}
}
==============================
package [Link];
public class VowelsPresentChecker {
public static void main(String[] args) {
if ([Link] == 0) {
[Link]("Please provide an input string.");
return;
}
String s = args[0].toLowerCase();
if ([Link](".*[aeiou].*")) {
[Link]("The given input contains vowels.");
} else {
[Link]("The given input does not contain vowels.");
}
}
}
================================
// Parallelly adding Two lists into new list
package [Link];
import [Link].*;
public class MergeTwoListsAlternatively {
public static void main(String[] args) {
List<Integer> list1 = [Link](1, 3, 5, 7);
List<Integer> list2 = [Link](2, 4, 6, 8, 10,12);
// Initialize list3 as a new ArrayList to store the interleaved elements
List<Integer> list3 = new ArrayList<>();
// Get the size of the smaller list to prevent IndexOutOfBoundsException
int size = [Link]([Link](), [Link]());
// Interleave elements from both lists
for (int i = 0; i < size; i++) {
[Link]([Link](i));
[Link]([Link](i));
}
// If list1 is longer, add the remaining elements
if ([Link]() > size) {
[Link]([Link](size, [Link]()));
}
// If list2 is longer, add the remaining elements
if ([Link]() > size) {
[Link]([Link](size, [Link]()));
}
// Print the interleaved list
[Link](list3);
}
}
=================================
// Remove Duplicates from String
import [Link].*;
public class FrequencyLettersRemove{
public static void main(String [] args){
String str = "abcabcdefghi";
Set<Character> hs = new HashSet<>();
for(char ch : [Link]()){
[Link](ch);
}
StringBuilder sb = new StringBuilder();
for(Character st : hs){
[Link](st);
}
[Link]([Link]());
}
===================================================
// Compare Two Strings WithOut Comparable and Comparator
package [Link];
import [Link];
public class CompareStringsWithOutComparableandComparator {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "hello";
if ([Link](str1, str2)) {
[Link]("Strings are equal.");
} else {
[Link]("Strings are not equal.");
}
}
}
==================================
// Write Odd and Even Numbers Using Two Threads
package [Link];
public class OddEven {
private static final Object lock = new Object();
public static void main(String[] args) {
Thread oddThread = new Thread(() -> {
for (int i = 1; i <= 9; i += 2) {
synchronized (lock) {
[Link](i);
[Link]();
try { [Link](); } catch (InterruptedException e) {}
}
}
});
Thread evenThread = new Thread(() -> {
for (int i = 2; i <= 10; i += 2) {
synchronized (lock) {
[Link](i);
[Link]();
try { [Link](); } catch (InterruptedException e) {}
}
}
});
[Link]();
[Link]();
}
}
===============================
// Print Names and count Using java 8
import [Link].*;
import [Link].*;
public class CountWords{
public static void main(String [] args){
String [] s =
{"Anjaneya","RamaChandra","Krishna","Gopala","Mukunda","Krishna"};
Map<String,Long> res = [Link](s).collect([Link](w-
>w,[Link]()));
[Link]((w,c)->[Link](w+"="+c));
}
}
=============================================
// Remove duplicate from a list of employee object based on empID using streams
import [Link].*;
import [Link];
class Employee {
private int empID;
private String name;
public Employee(int empID, String name) {
[Link] = empID;
[Link] = name;
}
public int getEmpID() {
return empID;
}
public String getName() {
return name;
}
@Override
public String toString() {
return "Employee{" + "empID=" + empID + ", name='" + name + '\'' + '}';
}
}
public class Main {
public static void main(String[] args) {
List<Employee> employees = [Link](
new Employee(101, "John"),
new Employee(102, "Alice"),
new Employee(101, "John"),
new Employee(103, "Bob"),
new Employee(102, "Alice")
);
List<Employee> uniqueEmployees = [Link]()
.collect([Link](Employee::getEmpID, e -> e, (e1, e2) ->
e1))
.values()
.stream()
.collect([Link]());
[Link]([Link]::println);
}
}
============================================