other
|
2025-12-09
|
salesforce
Q: 1. Preventing Duplicate Records with triggers and without trigger
Scenario: Ensure that no two accounts can have the same email address.
Question: How would you implement a trigger to enforce this rule?
trigger AccountPreventDuplicateEmail on Account (before insert, before update) {
// Collect Email values from incoming records
Set<String> incomingEmails = new Set<String>();
for (Account acc : Trigger.new) {
if (acc.Email__c != null) {
incomingEmails.add(acc.Email__c.trim().toLowerCase());
}
}
// Query existing accounts with same emails
Map<String, Account> existingEmailMap = new Map<String, Account>();
for (Account acc : [
SELECT Id, Email__c
FROM Account
WHERE Email__c IN :incomingEmails
]) {
existingEmailMap.put(acc.Email__c.toLowerCase(), acc);
}
// Add errors if duplicate detected
for (Account acc : Trigger.new) {
if (acc.Email__c != null) {
String email = acc.Email__c.trim().toLowerCase();
// Skip comparison with itself in update
if (existingEmailMap.containsKey(email)
&& existingEmailMap.get(email).Id != acc.Id) {
acc.Email__c.addError(
'An account with this email already exists (' +
existingEmailMap.get(email).Id +
'). Duplicates are not allowed.'
);
}
}
}
}
other
|
2025-12-09
|
salesforce
Q: 1. Preventing Duplicate Records with triggers and without trigger
Scenario: Ensure that no two accounts can have the same email address.
Question: How would you implement a trigger to enforce this rule?
1. Preventing Duplicates WITHOUT a Trigger (Best Practice)
Salesforce already provides built-in ways to enforce uniquenessβyou should always try these first.
Option A: Use a Unique Field
If Email__c is a custom field:
Go to Setup β Object Manager β Account β Fields & Relationships
Open the field Email__c
Check βUniqueβ
Save
Salesforce will automatically block inserts/updates that cause duplicates.
Option B: Use a Duplicate Rule + Matching Rule
This works for both standard and custom fields.
Steps
Setup β Duplicate Rules
New Rule β Account
Set Matching Rule on Email field
Choose action:
Block (to prevent duplicates completely)
Or Allow but Report
β No code needed.
This is recommended over triggers because it uses Salesforceβs built-in duplicate management.
β
2. Preventing Duplicates WITH a Trigger (When business logic requires it)
β When do we need a trigger?
When duplicate detection logic is more complex
When rules depend on multiple fields
When different actions are required for different profiles
other
|
2025-12-09
|
salesforce
Q: how to able to hide fields from manager in salesforce
1. Hide a field using Field-Level Security (FLS)
This is the proper way to prevent users (including managers) from seeing or editing a field anywhere in Salesforce.
Steps
Go to Setup
Search: Object Manager
Choose the object (e.g., Account, Contact, Opportunity)
Click Fields & Relationships
Choose the field you want to hide
Click Set Field-Level Security
Uncheck:
Visible (to completely hide field)
Or Read-Only (to prevent editing)
Click Save
β Result
Managers assigned to that profile cannot see the field anywhere
β not on layouts, reports, APIs, list views.
hcl
|
2025-12-09
|
javascript
Q: const x = {
2: "a",
1: "b",
3: "c",
2: "d"
}
console.log(Object.keys(x))
[1,2,3] =>2 :a
-------------------------------Wrong answer a->d
------------------------------------------
const obj = { a: { b: 1 } };
Object.freeze(obj);
obj.a.b = 99;
console.log(obj.a.b);
99
1. Duplicate keys overwrite previous ones
The key 2 appears twice:
2: "a",
...
2: "d" // overwrites previous value
Final object becomes:
{
1: "b",
2: "d",
3: "c"
}
--------------------------------------
function deepFreeze(obj) {
Object.freeze(obj);
Object.keys(obj).forEach(key => {
if (typeof obj[key] === 'object' && obj[key] !== null) {
deepFreeze(obj[key]);
}
});
return obj;
}
const o = deepFreeze({ a: { b: 1 } });
o.a.b = 99; // β fails silently in non-strict mode
console.log(o.a.b); // still 1
hcl
|
2025-12-09
|
javascript
Q:
const {length} = "abc";
console.log(length);
abc
-----------------------------------Wrong its answer -3
----------------------------------------------
let obj1 = {name : "Yash"};
let obj2 = {name : "Yash"};
console.log(obj1 === obj2);
True / true
---------------------------------- Wrong False / false77777
console.log([1, 2, 3] + [4, 5, 6]);
[1,2,3,4,5,6]
---------------------------------- Wrong Answer 1,2,34,5,6
const obj = { a: { b: 1 } };
Object.freeze(obj);
obj.a.b = 99;
console.log(obj.a.b);
99
-----------------------------------correct 99
const x = {
2: "a",
1: "b",
3: "c",
2: "d"
}
console.log(Object.keys(x))
[1,2,3] =>2 :a
-------------------------------Wrong answer a->d
1."abc" is a string
Strings in JavaScript behave like objects, and they have built-in properties such as .length.
2. Destructuring assignment
This syntax:7
const { length } = "abc";
means:
Get the property length from the string "abc" and store it in a variable named length.
So it is the same as doing:
const length = "abc".length;
3. "abc".length is 3
Because the string "abc" has three characters.
-----------------------------------------------
2.Explanation
Even with == (loose equality), JavaScript does not compare object values.
Both:
=== β strict equality
== β loose equality
compare object references, not contents.7
So:
obj1 points to one object in memory.77
obj2 points to a different object in memory.
Even though the values look identical, the references are different:
obj1 ---> { name: "Yash" } (memory address A)
obj2 ---> { name: "Yash" } (memory address B)
Therefore:
obj1 == obj2 // false
--------------------------------------------
4.Explanation
When you use the + operator with arrays, JavaScript converts both arrays to strings.
Step-by-step:
1. Arrays are converted to strings using .toString()
[1, 2, 3].toString() β "1,2,3"
[4, 5, 6].toString() β "4,5,6"
2. Then string concatenation happens:
"1,2,3" + "4,5,6" β "1,2,34,5,6"7
So the result is:
"1,2,34,5,6"
hcl
|
2025-12-09
|
mysql
Q: second highest salary or n highest salary
SELECT DISTINCT salary
FROM employees e1
WHERE (SELECT COUNT(DISTINCT salary)
FROM employees e2
WHERE e2.salary > e1.salary) = N-1;
hcl
|
2025-12-09
|
java
Q: int[] arr = {1, 2, 3, 7, 5,12};
int target = 12;
{1,2,3,5,7}
Output: [2, 4] (because 2 + 3 + 7 = 12)
By Java8
import java.util.stream.IntStream;
public class SubarraySumJava8 {
public static int[] findSubarray(int[] arr, int target) {
int[] result = {-1, -1};
int[] start = {0};
int[] sum = {0};
IntStream.range(0, arr.length).forEach(end -> {
sum[0] += arr[end];
while (sum[0] > target && start[0] <= end) {
sum[0] -= arr[start[0]];
start[0]++;
}
if (sum[0] == target) {
result[0] = start[0];
result[1] = end;
}
});
return result;
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 7, 5, 12};
int target = 12;
int[] result = findSubarray(arr, target);
System.out.println("[" + result[0] + ", " + result[1] + "]");
}
}
hcl
|
2025-12-09
|
java
Q: int[] arr = {1, 2, 3, 7, 5,12};
int target = 12;
{1,2,3,5,7}
Output: [2, 4] (because 2 + 3 + 7 = 12)
public class SubarraySum {
public static int[] findSubarray(int[] arr, int target) {
int start = 0;
int sum = 0;
for (int end = 0; end < arr.length; end++) {
sum += arr[end];
while (sum > target && start <= end) {
sum -= arr[start];
start++;
}
if (sum == target) {
return new int[]{start, end}; // inclusive indices
}
}
return new int[]{-1, -1}; // not found
}
public static void main(String[] args) {
int[] arr = {1, 2, 3, 7, 5, 12};
int target = 12;
int[] result = findSubarray(arr, target);
System.out.println("[" + result[0] + ", " + result[1] + "]");
}
}
Other
|
2025-09-24
|
java
Q: Java 8 Stream + Lambda Expression Solution
How do you find frequency of each character in a string using Java 8 streams "Java Concept Of The Day" {a=3, c=1, C=1, D=1, e=2, f=1, h=1, J=1, n=1, O=1, o=1, p=1, T=1, t=1, v=1, y=1}
import java.util.Map;
import java.util.stream.Collectors;
public class CharFrequency {
public static void main(String[] args) {
String input = "Java Concept Of The Day";
Map<Character, Long> freq = input.chars()
.mapToObj(c -> (char) c) // convert int -> Character
.filter(ch -> ch != ' ') // ignore spaces
.collect(Collectors.groupingBy(ch -> ch, // group by character
Collectors.counting())); // count occurrences
System.out.println(freq);
}
}
Infosys
|
2025-09-09
|
java
Q: Part-2
define employee
import java.util.*;
import java.util.stream.*;
class Employee{
Integer id;
String name;
String dept;
double salary;
public Employee(int id,String name,String dept,double salary){
this.id = id;
this.name = name;
this.dept = dept;
this.salary = salary;
}
public int getId(){
return id;
}
public String getName(){
return name;
}
public double getSalary(){
return salary;
}
public String getDept(){
return dept;
}
@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", department='" + dept + '\'' +
", salary=" + salary +
'}';
}
}
Infosys
|
2025-09-09
|
java
Q: You said:
List<Employee> employees = Arrays.asList(
new Employee(101, "Alice", "HR", 50000),
new Employee(102, "Shekhar", "IT", 90000),
new Employee(103, "Sunil", "Finance", 30000),
new Employee(104, "Preeti", "IT", 20000),
new Employee(105, "Balaji", "HR", 70000),
new Employee(106, "Riya", "Finance", 100000),
new Employee(107, "Kaustub", "IT", 80000)
);
1: Filter employees with salary > 60000
2: Group employees by department and count.
3: Find highest paid employee in each department.
4: Sort employees by salary in descending order.
class Main {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee(101, "Alice", "HR", 50000),
new Employee(102, "Shekhar", "IT", 90000),
new Employee(103, "Sunil", "Finance", 30000),
new Employee(104, "Preeti", "IT", 20000),
new Employee(105, "Balaji", "HR", 70000),
new Employee(106, "Riya", "Finance", 100000),
new Employee(107, "Kaustub", "IT", 80000)
);
List<Employee> output1 = employees.stream().filter(e->e.getSalary() > 60000).collect(Collectors.toList());
output1.forEach(System.out::println);
Map<String,Long> output2 = employees.stream().collect(Collectors.groupingBy(Employee::getDept, Collectors.counting()));
output2.forEach((dept,count)->System.out.println(dept+"---"+count));
Map<String,Optional<Employee>> output3= employees.stream().collect(Collectors.groupingBy(Employee::getDept,Collectors.maxBy(Comparator.comparingDouble(Employee::getSalary))));
output3.forEach((dept,empOpt)->System.out.println(dept+"---"+empOpt.orElse(null)));
System.out.println("\nEmployees sorted by salary (descending):");
List<Employee> output4 = employees.stream().sorted(Comparator.comparingDouble(Employee::getSalary).reversed()).collect(Collectors.toList());
output4.forEach(System.out::println);
//System.out.println("Try programiz.pro"+ employees);
//System.out.println("Try programiz.pro"+ output1);
}
}
Other
|
2025-09-02
|
javascript
Q: [[1,2,3], [4,5,6], [7.8,9], [10,11,[12,13,14]];
without using inbuild function
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, [12, 13, 14]]
];
function flatten(array) {
let result = [];
for (let i = 0; i < array.length; i++) {
if (Array.isArray(array[i])) {
// if element is an array β recurse
result = result.concat(flatten(array[i]));
} else {
// if element is not an array β push
result.push(array[i]);
}
}
return result;
}
console.log(flatten(arr));
//with inbuild
const flatArr = arr.flat(Infinity);
console.log(flatArr);
Other
|
2025-08-28
|
java
Q: Reverse the string
input :"Read input from STDIN"
output: "STDIN input from read"
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class Main {
public static void main(String[] args) {
String s = "read from input STDIN";
String rev = Arrays.stream(s.split(" ")).collect(Collectors.collectingAndThen(Collectors.toList(),list->{
Collections.reverse(list);
return String.join(" ",list);
} ));
System.out.println("Reverse String "+rev);
}
}
Other
|
2025-08-28
|
java
Q: Find second highest number
1, 4, 8, 9, 10, 20
output:10 //second highest
import java.util.*;
import java.util.stream.*;
class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 4, 8, 9, 10, 20);
int secondHighest = numbers.stream()
.sorted(Comparator.reverseOrder())
.skip(1) // skip the first (highest)
.findFirst()
.get();
System.out.println("Second highest: " + secondHighest);
}
}
Other
|
2025-08-26
|
java
Q: Given a list of words, group them into lists of anagrams with java 8 Input: ["bat", "tab", "eat", "tea", "tan", "nat"] Output: [[bat, tab], [eat, tea], [tan, nat]];
import java.util.*;
import java.util.stream.Collectors;
public class AnagramGrouper {
public static void main(String[] args) {
List<String> words = Arrays.asList("bat", "tab", "eat", "tea", "tan", "nat");
Map<String, List<String>> grouped = words.stream()
.collect(Collectors.groupingBy(word -> {
char[] chars = word.toCharArray();
Arrays.sort(chars); // sort characters in word
return new String(chars); // use sorted string as key
}));
List<List<String>> result = new ArrayList<>(grouped.values());
System.out.println(result);
}
}
Other
|
2025-08-23
|
java
Q:
IT -> [1 - Alice, 3 - Charlie]
HR -> [2 - Bob, 5 - Eva]
Finance -> [4 - David]
import java.util.*;
import java.util.stream.Collectors;
class Employee {
private int id;
private String name;
private String department;
// Constructor
public Employee(int id, String name, String department) {
this.id = id;
this.name = name;
this.department = department;
}
// Getters
public int getId() { return id; }
public String getName() { return name; }
public String getDepartment() { return department; }
@Override
public String toString() {
return id + " - " + name;
}
}
public class GroupByDepartmentExample {
public static void main(String[] args) {
List<Employee> employees = Arrays.asList(
new Employee(1, "Alice", "IT"),
new Employee(2, "Bob", "HR"),
new Employee(3, "Charlie", "IT"),
new Employee(4, "David", "Finance"),
new Employee(5, "Eva", "HR")
);
// Group employees by department
Map<String, List<Employee>> employeesByDept = employees.stream()
.collect(Collectors.groupingBy(Employee::getDepartment));
// Print result
employeesByDept.forEach((dept, empList) -> {
System.out.println(dept + " -> " + empList);
});
}
}
Other
|
2025-08-22
|
java
Q: Find the youngest student
import java.util.*;
public class YoungestStudent {
public static void main(String[] args) {
List<Student> students = Arrays.asList(
new Student("Alice", 22),
new Student("Bob", 19),
new Student("Charlie", 21),
new Student("Daisy", 20)
);
Student youngest = students.stream()
.min(Comparator.comparingInt(Student::getAge))
.orElse(null);
System.out.println("Youngest student: " + youngest);
}
}
Other
|
2025-08-22
|
java
Q: Find the longest/highest length of the string ("apple", "banana", "pineapple", "kiwi")
import java.util.List;
import java.util.Comparator;
public class MaxLengthString {
public static void main(String[] args) {
List<String> list = List.of("abc", "bdcd", "defgh");
String longest = list.stream()
.max(Comparator.comparingInt(String::length))
.orElse("");
System.out.println("Longest string: " + longest);
System.out.println("Length: " + longest.length());
}
}
Other
|
2025-08-22
|
java
Q: Find the longest/highest length of the string ("apple", "banana", "pineapple", "kiwi")
import java.util.*;
class Main {
public static void main(String[] args) {
List<String> list = Arrays.asList("apple", "banana", "pineapple", "kiwi");
list.stream()
.max(Comparator.comparingInt(String::length))
.ifPresent(s -> System.out.println("Longest: " + s + " (length " + s.length() + ")"));
System.out.println("Try programiz.pro");
}
}
Wipro
|
2025-08-13
|
java
Q: Find the frequency of repeated elements
int[] list1 = {2,4,5,7,3,3,8,9,2,4,7,12};
output: {2=2, 3=2, 4=2, 5=1, 7=2, 8=1, 9=1, 12=1}
import java.util.*;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
int[] list1 = {2,4,5,7,3,3,8,9,2,4,7,12};
int count = 0;
Map<Integer, Integer> list3 = new HashMap<>();
for(int i=0;i<list1.length;i++){
//list3.put(list1[i],count);
if(list3.containsKey(list1[i])){
int count1 = list3.get(list1[i]);
count1 +=1;
list3.put(list1[i],count1);
}else{
list3.put(list1[i],1);
}
}
System.out.println(list3);
}
}
Other
|
2025-08-09
|
java
Q: Repeated and non repeated
{1, 2, 3, 2, 4, 5, 3, 6, 7, 7}
Repeated numbers: [2, 3, 7]
Non-repeated numbers: [1, 4, 5, 6]
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class RepeatedAndNonRepeated {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 2, 4, 5, 3, 6, 7, 7);
// Count occurrences
Map<Integer, Long> frequencyMap = numbers.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// Repeated numbers (count > 1)
List<Integer> repeated = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
// Non-repeated numbers (count == 1)
List<Integer> nonRepeated = frequencyMap.entrySet().stream()
.filter(entry -> entry.getValue() == 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("Repeated numbers: " + repeated);
System.out.println("Non-repeated numbers: " + nonRepeated);
}
}
Other
|
2025-08-08
|
java
Q: Not repeated character from the string
S="Mazharalikhan"
output: Not Duplicate key[A, r, i, z, k, l, M, n]
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
//List<String> myList =
String s ="MazharAlikhan";
Map<Character,Long> myList =s.chars()
.mapToObj(c -> (char) c) // convert int to Character
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
List<Character> duplicates = myList.entrySet().stream().filter(e->e.getValue() == 1).map(Map.Entry::getKey).collect(Collectors.toList());
System.out.println("Duplicate key"+ duplicates);
}
}
Other
|
2025-08-08
|
java
Q: Find the duplicate letters from the string
S="Mazharalikhan"
Duplicate characters: [a, h]
Character count: {a=4, A=1, M=1, z=1, r=1, l=1, i=1, k=1, h=2, n=1}
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
String s = "MazharAlikhan";
// Count occurrences of each character
Map<Character, Long> charCount = s.chars()
.mapToObj(c -> (char) c) // convert int to Character
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// Filter and collect duplicates
List<Character> duplicates = charCount.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("Duplicate characters: " + duplicates);
System.out.println("Character count: " + charCount);
}
}
Other
|
2025-07-24
|
java
Q: Balancing brackets
'{[()]}' -- // true
'{[(123])}' // false
'{{(1244}}' // false
import java.util.*;
public class BalancedBrackets {
public static boolean isBalanced(String s) {
Deque<Character> stack = new ArrayDeque<>();
Map<Character, Character> pairs = Map.of(')', '(', ']', '[', '}', '{');
for (char ch : s.toCharArray()) {
if (pairs.containsValue(ch)) {
stack.push(ch);
} else if (pairs.containsKey(ch)) {
if (stack.isEmpty() || stack.pop() != pairs.get(ch)) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
System.out.println(isBalanced("{[()]}")); // true
System.out.println(isBalanced("{[(123])}")); // false
System.out.println(isBalanced("{{(1244}}")); // false
}
}
Cognizant
|
2025-07-22
|
java
Q: repeated count
String a = "MAZHAR ALI KHAN PATHAN";
output: {A=5, H=2, I=1, K=1, L=1, M=1, N=2, P=1, R=1, Z=1}
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CharFrequency {
public static void main(String[] args) {
String a = "MAZHAR ALI KHAN PATHAN";
Map<Character, Long> output = a.chars()
.mapToObj(c -> (char) c)
.filter(c -> c != ' ') // Ignore spaces
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting())
);
System.out.println("output: " + output);
}
}
Infosys
|
2025-07-17
|
java
Q: Given a list of integers, find out all the numbers starting with 1 using Stream functions?(10,15,8,49,25,98,32)
output:[10, 15]
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 15, 8, 49, 25, 98, 32);
List<Integer> result = numbers.stream()
.map(String::valueOf) // Convert integers to strings
.filter(s -> s.startsWith("1")) // Filter strings starting with "1"
.map(Integer::valueOf) // Convert back to integers
.collect(Collectors.toList()); // Collect as a list
System.out.println(result); // Output: [10, 15]
}
}
Other
|
2025-07-05
|
java
Q: print the duplicate from the list (1, 2, 3, 2, 4, 5, 3, 6, 7, 7);
Output:Duplicates: [2, 3, 7]
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
List<Integer> a1 = Arrays.asList(1, 2, 3, 2, 4, 5, 3, 6, 7, 7);
List<Integer> a2 = a1.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toList());
System.out.println("Duplicates: " + a2);
}
}
Other
|
2025-07-04
|
java
Q: int[] list1 = {1, 2, 3, 4, 5, 2, 1};
int[] list2 = {3, 4, 5, 6, 7};
Common Elements: [3, 4, 5]
Union: [1, 2, 3, 4, 5, 6, 7]
Frequencies in list1:{1 -> 2,2 -> 2,3 -> 1,4 -> 1,5 -> 1}
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int[] list1 = {1, 2, 3, 4, 5, 2, 1};
int[] list2 = {3, 4, 5, 6, 7};
// Convert arrays to lists
List<Integer> l1 = Arrays.stream(list1).boxed().collect(Collectors.toList());
List<Integer> l2 = Arrays.stream(list2).boxed().collect(Collectors.toList());
// 1. Common elements
List<Integer> common = l1.stream()
.distinct()
.filter(l2::contains)
.collect(Collectors.toList());
System.out.println("Common Elements: " + common); // [3, 4, 5]
// 2. Union
List<Integer> union = Stream.concat(l1.stream(), l2.stream())
.distinct()
.sorted()
.collect(Collectors.toList());
System.out.println("Union: " + union); // [1, 2, 3, 4, 5, 6, 7]
// 3. Frequency of each number in list1
Map<Integer, Long> freqMap = l1.stream()
.collect(Collectors.groupingBy(
Function.identity(),
Collectors.counting()
));
System.out.println("Frequencies in list1:");
freqMap.forEach((key, value) -> System.out.println(key + " -> " + value));
}
}
Other
|
2025-06-28
|
java
Q: Count the repeated character from a string
"Programming"
Output :{p=1, a=1, r=2, g=2, i=1, m=2, n=1, o=1}
import java.util.*;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
String s ="programming";
Map<Character,Long> a = s.chars().mapToObj(c->(char) c).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("myOutput"+ a);
}
}
Other
|
2025-06-26
|
java
Q: Enter the balls and count the balls color and its length
result: {red=2, green=2, black=1}
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> bucket = new ArrayList<>();
System.out.println("Enter items (type 'count' to stop):");
while(true){
System.out.println("Enter the ball:");
String input = sc.nextLine();
if (input.equalsIgnoreCase("count")) {
break; // Exit the loop
} else {
bucket.add(input); // Add input to the list
}
}
// List<String> bucket = Arrays.asList("green", "black","red","green","red","orange","red","white");
if(bucket.size() >2){
Map<String, Long> result = bucket.stream().collect(Collectors.groupingBy(e->e,Collectors.counting()));
System.out.println("result"+ result);
}
}
}
Other
|
2025-06-26
|
java
Q: bucket: ("green", "black","red","green","red","orange","red","white");
Output: {black=1, red=3, orange=1, white=1, green=2}
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
List<String> bucket = Arrays.asList("green", "black","red","green","red","orange","red","white");
Map<String, Long> result = bucket.stream().collect(Collectors.groupingBy(e->e,Collectors.counting()));
System.out.println("result"+ result);
}
}
Infosys
|
2025-06-23
|
java
Q: define an object
public class Main {
public static void main(String[] args) {
// Option 1: Using Arrays.asList
List<Employee> employees = Arrays.asList(
new Employee(1, "Alice", 50000),
new Employee(2, "Bob", 60000),
new Employee(3, "Charlie", 55000)
);
// Option 2: Using Stream.of
List<Employee> employees2 = Stream.of(
new Employee(4, "David", 70000),
new Employee(5, "Eva", 75000)
).collect(Collectors.toList());
// Print list
employees.forEach(System.out::println);
}
}
Deloitte
|
2025-06-20
|
java
Q: Bubble sort
public class BubbleSortExample {
public static void main(String[] args) {
int[] arr = {5, 1, 4, 2, 8};
// Bubble sort logic
for (int i = 0; i < arr.length - 1; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
// swap arr[j] and arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
// Print sorted array
for (int num : arr) {
System.out.print(num + " ");
}
}
}
Infosys
|
2025-06-23
|
java
Q: sorted by descending order - 5, 2, 9, 1, 7
// Output: [9, 7, 5, 2, 1]
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class DescendingSortExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 2, 9, 1, 7);
List<Integer> sortedDesc = numbers.stream()
.sorted((a, b) -> b - a) // or Comparator.reverseOrder()
.collect(Collectors.toList());
System.out.println(sortedDesc); // Output: [9, 7, 5, 2, 1]
}
}
Infosys
|
2025-06-13
|
java
Q: Find the common element from the list
list a = {"AA","BB","CC","AA"} list b ={"BB","CC"}
Output:Common elements: [BB, CC]
import java.util.*;
import java.util.stream.Collectors;
public class CommonElements {
public static void main(String[] args) {
List<String> listA = Arrays.asList("AA", "BB", "CC", "AA");
List<String> listB = Arrays.asList("BB", "CC");
// Get common elements
List<String> common = listA.stream()
.filter(listB::contains)
.collect(Collectors.toList());
System.out.println("Common elements: " + common);
}
}
Other
|
2025-06-11
|
java
Q: print all the numbers which are duplicate in the list
output:Duplicate elements: [1, 2, 6, 45]
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Main
{
public static void main(String args[]) {
List<Integer> myList = Arrays.asList(1, 1, 85, 6, 2, 3, 65, 6, 45, 45, 5662, 2582, 2, 2, 266, 666, 656);
Set<Integer> duplicates = myList.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.filter(e -> e.getValue() > 1)
.map(Map.Entry::getKey)
.collect(Collectors.toSet());
System.out.println("Duplicate elements: " + duplicates);
}
}
Infosys
|
2025-06-03
|
java
Q: Find the vowels
input: test
output: Vowel is 1
Constraint : 3
import java.util.*;
class Main {
public static void main(String[] args) {
System.out.println("Try programiz.pro");
String s = "aeou";
Integer a = 0;
Integer b = 0;
List<String> vowel = Arrays.asList("a","e","i","o","u");
char[] c = s.toCharArray();
for(int i=0;i<c.length;i++){
if(vowel.contains(String.valueOf(c[i]))){
a++;
}else{
b++;
}
}
System.out.println("Vowel is"+ a);
System.out.println("Constant is"+ b);
}
}
Wipro
|
2025-05-31
|
java
Q: Write a Java 8 program to concatenate two Streams?
l1= Arrays.asList("Java", "8");
l2= Arrays.asList("explained", "through", "programs");
//l1.concat(l2);
l1.add(l2);
output: [Java, 8, explained, through, programs]
List<String> combined = Stream.concat(l1.stream(), l2.stream())
.collect(Collectors.toList());
System.out.println(combined); // Output: [Java, 8, explained, through, programs]
Wipro
|
2025-05-31
|
java
Q: How to count each element/word from the String ArrayList in Java8?
"AA", "BB", "AA", "CC"
Output:
{CC=1, BB=1, AA=2}
import java.util.*;
import java.util.stream.Collectors;
public class WordCount {
public static void main(String[] args) {
List<String> list = Arrays.asList("AA", "BB", "AA", "CC");
Map<String, Long> frequencyMap = list.stream()
.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
System.out.println(frequencyMap);
}
}
Capgemini
|
2025-05-30
|
java
Q: find the count of repeated string
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
String s = "programming";
// Calculate the frequency of each character
Map<Character, Long> a = s.chars()
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// Print the frequency map
a.forEach((key, value) -> System.out.println(key + ": " + value));
}
}
Capgemini
|
2025-05-29
|
java
Q: java Code for string manipulation and finding distinct characters in String.
Input string: programming
Distinct characters: [p, r, o, g, a, m, i, n]
import java.util.*;
import java.util.stream.Collectors;
public class DistinctCharacters {
public static void main(String[] args) {
String input = "programming";
// Convert to lowercase (optional) to treat 'A' and 'a' as the same
String normalized = input.toLowerCase();
// Get distinct characters
List<Character> distinctChars = normalized.chars()
.mapToObj(c -> (char) c)
.distinct()
.collect(Collectors.toList());
// Print results
System.out.println("Input string: " + input);
System.out.println("Distinct characters: " + distinctChars);
}
}
Other
|
2025-05-28
|
java
Q: Group by Department Using Stream (Custom Object)
import java.util.*;
import java.util.stream.Collectors;
class Employee {
String name;
String dept;
Employee(String name, String dept) {
this.name = name;
this.dept = dept;
}
}
public class GroupByDept {
public static void main(String[] args) {
List<Employee> list = Arrays.asList(
new Employee("Alice", "IT"),
new Employee("Bob", "HR"),
new Employee("Charlie", "IT")
);
Map<String, List<Employee>> grouped = list.stream()
.collect(Collectors.groupingBy(e -> e.dept));
grouped.forEach((k, v) -> {
System.out.println(k + ": " + v.stream().map(e -> e.name).toList());
});
}
}
Other
|
2025-05-28
|
java
Q: Reverse Words in a Sentence
public class ReverseWords {
public static void main(String[] args) {
String sentence = "Java is fun";
String[] words = sentence.split(" ");
StringBuilder sb = new StringBuilder();
for (int i = words.length - 1; i >= 0; i--) {
sb.append(words[i]).append(" ");
}
System.out.println("Reversed: " + sb.toString().trim());
}
}
Other
|
2025-05-28
|
java
Q: Check Anagram Strings
import java.util.Arrays;
public class AnagramCheck {
public static void main(String[] args) {
String str1 = "listen";
String str2 = "silent";
char[] ch1 = str1.toCharArray();
char[] ch2 = str2.toCharArray();
Arrays.sort(ch1);
Arrays.sort(ch2);
boolean result = Arrays.equals(ch1, ch2);
System.out.println(result ? "Anagram" : "Not Anagram");
}
}
Other
|
2025-05-28
|
java
Q: Find Missing Number in Array from 1 to N
public class MissingNumber {
public static void main(String[] args) {
int[] arr = {1, 2, 4, 5};
int n = 5;
int expectedSum = n * (n + 1) / 2;
int actualSum = 0;
for (int num : arr) actualSum += num;
System.out.println("Missing number: " + (expectedSum - actualSum));
}
}
Other
|
2025-05-28
|
java
Q: Palindrome String
public class Palindrome {
public static void main(String[] args) {
String str = "madam";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(str.equals(reversed) ? "Palindrome" : "Not a palindrome");
}
}
Other
|
2025-05-28
|
java
Q: Check if a Number is Prime
public class PrimeCheck {
public static void main(String[] args) {
int num = 17;
boolean isPrime = true;
if (num <= 1) isPrime = false;
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) isPrime = false;
}
System.out.println(num + " is prime? " + isPrime);
}
}
Other
|
2025-05-28
|
java
Q: Reverse a String
public class ReverseString {
public static void main(String[] args) {
String str = "hello";
String reversed = new StringBuilder(str).reverse().toString();
System.out.println("Reversed: " + reversed);
}
}
Other
|
2025-05-28
|
java
Q: Convert a List of Strings to Uppercase Using Streams
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class ConvertToUppercase {
public static void main(String[] args) {
List<String> words = Arrays.asList("java", "python", "javascript");
List<String> uppercasedWords = words.stream()
.map(String::toUpperCase) // Convert each string to uppercase
.collect(Collectors.toList()); // Collect results
System.out.println("Uppercased words: " + uppercasedWords);
}
}
Output:
Uppercased words: [JAVA, PYTHON, JAVASCRIPT]
Other
|
2025-05-28
|
java
Q: Remove Duplicates from a List Using Streams
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class RemoveDuplicates {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 2, 3, 4, 4, 5);
List<Integer> uniqueNumbers = numbers.stream()
.distinct() // Remove duplicates
.collect(Collectors.toList()); // Collect the unique values
System.out.println("Unique numbers: " + uniqueNumbers);
}
}
Output:
Unique numbers: [1, 2, 3, 4, 5]
Other
|
2025-05-28
|
java
Q: Flatten a List of Lists Using Streams
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FlattenList {
public static void main(String[] args) {
List<List<Integer>> listOfLists = Arrays.asList(
Arrays.asList(1, 2, 3),
Arrays.asList(4, 5, 6),
Arrays.asList(7, 8, 9)
);
List<Integer> flattenedList = listOfLists.stream()
.flatMap(List::stream) // Flatten the lists
.collect(Collectors.toList()); // Collect as list
System.out.println("Flattened list: " + flattenedList);
}
}
Output:
Flattened list: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Other
|
2025-05-28
|
java
Q: Filter and Collect Even Numbers Greater Than 5 Using Stream
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class FilterEvenNumbers {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 6, 8, 5, 10, 7);
List<Integer> result = numbers.stream()
.filter(n -> n > 5 && n % 2 == 0) // Filter even numbers > 5
.collect(Collectors.toList()); // Collect as list
System.out.println("Even numbers greater than 5: " + result);
}
}
Output:
Even numbers greater than 5: [6, 8, 10]
Other
|
2025-05-28
|
java
Q: Find the Average of Numbers in a List Using Streams
import java.util.Arrays;
import java.util.List;
public class AverageOfNumbers {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(10, 20, 30, 40, 50);
double average = numbers.stream()
.mapToInt(Integer::intValue) // Convert to IntStream
.average() // Calculate the average
.orElse(0); // Provide default value if empty
System.out.println("Average: " + average);
}
}
Output:
Average: 30.0
Other
|
2025-05-28
|
java
Q: Sort a List of Strings by Length Using Streams
import java.util.Arrays;
import java.util.List;
public class SortStringsByLength {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "cherry", "date");
List<String> sortedWords = words.stream()
.sorted((w1, w2) -> Integer.compare(w1.length(), w2.length()))
.toList(); // Collect the results
System.out.println("Sorted words by length: " + sortedWords);
}
}
Output:
Sorted words by length: [date, apple, cherry, banana]
Other
|
2025-05-28
|
java
Q: Count the Occurrences of a Character in a String Using Streams
import java.util.stream.Stream;
public class CountCharacterOccurrences {
public static void main(String[] args) {
String input = "programming";
long count = input.chars() // Convert string to IntStream
.filter(c -> c == 'r') // Filter 'r' characters
.count(); // Count occurrences
System.out.println("Occurrences of 'r': " + count);
}
}
Output:
Occurrences of 'r': 2
Other
|
2025-05-28
|
java
Q: Find the Maximum Value in a List Using Streams
import java.util.Arrays;
import java.util.List;
public class MaxValue {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(5, 3, 7, 2, 9, 12, 8);
int max = numbers.stream()
.max(Integer::compare)
.get(); // Get the maximum value
System.out.println("Maximum value: " + max);
}
}
Output:
Maximum value: 12
Other
|
2025-05-28
|
java
Q: Find the Sum of Even Numbers in a List Using Streams
import java.util.Arrays;
import java.util.List;
public class SumEvenNumbers {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
int sum = numbers.stream()
.filter(n -> n % 2 == 0) // Filter even numbers
.mapToInt(Integer::intValue) // Convert to int
.sum(); // Sum them up
System.out.println("Sum of even numbers: " + sum);
}
}
Output:
Sum of even numbers: 30
Other
|
2025-05-28
|
javascript
Q: Write a program 1231 reverse this string . Output should be 1321
const number = 1231;
function reverseNumber(num) {
// Convert the number to a string, reverse it and join back to form the reversed string
return num.toString().split('').reverse().join('');
}
console.log("Reversed number:", reverseNumber(number));
Other
|
2025-05-28
|
java
Q: Write a program 1231 reverse this string . Output should be 1321
public class ReverseNumber {
public static void main(String[] args) {
int number = 1231;
String reversed = reverseNumber(number);
System.out.println("Reversed number: " + reversed);
}
public static String reverseNumber(int num) {
// Convert the number to a string
String numStr = Integer.toString(num);
// Create a StringBuilder and reverse the string
StringBuilder sb = new StringBuilder(numStr);
sb.reverse();
return sb.toString();
}
}
Other
|
2025-05-28
|
javascript
Q: Find the second largest number in an array:
const input = [5, 6, 3, 0, 11, 54, 99, 1, 2];
function findSecondLargest(arr) {
// Remove duplicates and sort the array in descending order
const uniqueArr = [...new Set(arr)].sort((a, b) => b - a);
// Check if there's at least two numbers
if (uniqueArr.length < 2) {
return "Array does not have a second largest number.";
}
return uniqueArr[1]; // Return the second largest number
}
console.log(findSecondLargest(input));
// Output: 54
Other
|
2025-05-28
|
java
Q: Find the second largest number in an array:
import java.util.Arrays;
public class SecondLargestNumber {
public static void main(String[] args) {
int[] input = {5, 6, 3, 0, 11, 54, 99, 1, 2};
System.out.println("Second largest number: " + findSecondLargest(input));
}
public static int findSecondLargest(int[] arr) {
// Sort the array in descending order
Arrays.sort(arr);
// Check if there are at least two distinct numbers
int largest = arr[arr.length - 1]; // Largest number
int secondLargest = Integer.MIN_VALUE;
// Traverse from the second last element to find second largest
for (int i = arr.length - 2; i >= 0; i--) {
if (arr[i] != largest) {
secondLargest = arr[i];
break;
}
}
// If second largest is still the minimum value, return an error message
if (secondLargest == Integer.MIN_VALUE) {
System.out.println("No second largest number found.");
return -1;
}
return secondLargest;
}
}
Other
|
2025-05-28
|
javascript
Q: Program that takes the input array and returns the sum of all positive numbers:
const input = [1, -4, 12, 0, -3, 29, -150];
function sumPositiveNumbers(arr) {
return arr
.filter(num => num > 0) // Keep only positive numbers
.reduce((sum, num) => sum + num, 0); // Sum them
}
console.log(sumPositiveNumbers(input));
// Output: 42
Other
|
2025-05-28
|
java
Q: Program that takes the input array and returns the sum of all positive numbers:
public class SumOfPositives {
public static void main(String[] args) {
int[] input = {1, -4, 12, 0, -3, 29, -150};
int sum = 0;
for (int num : input) {
if (num > 0) {
sum += num;
}
}
System.out.println("Sum of positive numbers: " + sum);
}
}
Other
|
2025-05-28
|
java
Q: Find the Factorial number like 12 -> β2 2 3β and 315 -> β3 3 5 7β
import java.util.*;
public class PrimeFactors {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
System.out.print("Prime factors: ");
for (int i = 2; i <= number; i++) {
while (number % i == 0) {
System.out.print(i + " ");
number /= i;
}
}
scanner.close();
}
}
Other
|
2025-05-28
|
java
Q: Write a program by using Functional Interface Predicate lower to upper case
import java.util.function.Predicate;
public class PredicateUppercaseExample {
public static void main(String[] args) {
String input = "hello world";
// Predicate to check if the string is in lowercase
Predicate<String> isLowerCase = str -> str.equals(str.toLowerCase());
if (isLowerCase.test(input)) {
String upperCaseStr = input.toUpperCase();
System.out.println("Converted to uppercase: " + upperCaseStr);
} else {
System.out.println("Input is not all lowercase.");
}
}
}
If user enter the input from System by using scanner
import java.util.Scanner;
import java.util.function.Predicate;
public class PredicateUppercaseExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();
// Predicate to check if the string is all lowercase
Predicate<String> isLowerCase = str -> str.equals(str.toLowerCase());
if (isLowerCase.test(input)) {
String upperCaseStr = input.toUpperCase();
System.out.println("Converted to uppercase: " + upperCaseStr);
} else {
System.out.println("Input is not all lowercase. No conversion applied.");
}
scanner.close();
}
}
Other
|
2025-05-28
|
java
Q: Write the program to find a perfect number
import java.util.Scanner;
public class PerfectNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to check if it's a perfect number: ");
int number = scanner.nextInt();
int sum = 0;
// Find all divisors less than the number
for (int i = 1; i < number; i++) {
if (number % i == 0) {
sum += i; // Add divisor to sum
}
}
// Check if sum of divisors equals the original number
if (sum == number) {
System.out.println(number + " is a Perfect Number.");
} else {
System.out.println(number + " is NOT a Perfect Number.");
}
scanner.close();
}
}
Capgemini
|
2025-05-28
|
java
Q: Write a Java 8 program to check if any number in a list is even.
import java.util.Arrays;
import java.util.List;
public class CheckEven {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(11, 23, 45, 62, 77);
boolean hasEven = numbers.stream()
.anyMatch(num -> num % 2 == 0);
if (hasEven) {
System.out.println("The list contains at least one even number.");
} else {
System.out.println("The list contains only odd numbers.");
}
}
}
Capgemini
|
2025-05-28
|
java
Q: String str = "BAR2024JAN19"; //sperate char value from string using java 8
import java.util.stream.Collectors;
public class SplitString {
public static void main(String[] args) {
String str = "BAR2024JAN19";
String letters = str.chars()
.filter(Character::isLetter)
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
String digits = str.chars()
.filter(Character::isDigit)
.mapToObj(c -> String.valueOf((char) c))
.collect(Collectors.joining());
System.out.println("Letters: " + letters); // Output: BARJAN
System.out.println("Digits: " + digits); // Output: 202419
}
}
Capgemini
|
2025-05-28
|
java
Q: 12345
1234
123
12
1
public class NumberPattern {
public static void main(String[] args) {
int n = 5; // max number
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++) {
System.out.print(j);
}
System.out.println();
}
}
}
Cognizant
|
2025-05-28
|
java
Q: Write a Java program to check if a vowel is present in a string.
Output:The string contains at least one vowel
import java.util.Scanner;
public class VowelChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine().toLowerCase(); // make case-insensitive
if (containsVowel(input)) {
System.out.println("The string contains at least one vowel.");
} else {
System.out.println("The string does not contain any vowels.");
}
scanner.close();
}
public static boolean containsVowel(String str) {
return str.matches(".*[aeiou].*");
}
}
Cognizant
|
2025-05-28
|
java
Q: List<Employee> empList = // 150 employees in this list
How to find howmany male and female by stream
Output: Male count: 1
Female count: 2
import java.util.*;
import java.util.stream.Collectors;
public class GenderCount {
public static void main(String[] args) {
List<Employee> empList = List.of(
new Employee("Alice", "Female"),
new Employee("Bob", "Male"),
new Employee("Eve", "Female")
// ... assume 150 employees
);
Map<String, Long> genderCount = empList.stream()
.collect(Collectors.groupingBy(Employee::getGender, Collectors.counting()));
System.out.println("Male count: " + genderCount.getOrDefault("Male", 0L));
System.out.println("Female count: " + genderCount.getOrDefault("Female", 0L));
}
}
HCL
|
2025-05-28
|
java
Q: Find the largest length of string in a list
list={"abc","bdcd","defgh"};
Output:
Longest string: defgh
Length: 5
import java.util.List;
import java.util.Comparator;
public class MaxLengthString {
public static void main(String[] args) {
List<String> list = List.of("abc", "bdcd", "defgh");
String longest = list.stream()
.max(Comparator.comparingInt(String::length))
.orElse("");
System.out.println("Longest string: " + longest);
System.out.println("Length: " + longest.length());
}
}
Other
|
2025-05-24
|
mysql
Q: Find the 4th, 5th, 6th highest salaries in mysql
SELECT salary
FROM employees
ORDER BY salary DESC
LIMIT 3 OFFSET 3;
Wipro
|
2025-05-26
|
java
Q: String[] A = {"abab", "ab", "abcd"}; by using Stream
output: ab
import java.util.Arrays;
public class LongestCommonPrefixStream {
public static String findLCP(String[] arr) {
if (arr == null || arr.length == 0) return "";
return Arrays.stream(arr)
.reduce((s1, s2) -> {
int i = 0;
while (i < s1.length() && i < s2.length() && s1.charAt(i) == s2.charAt(i)) {
i++;
}
return s1.substring(0, i);
})
.orElse("");
}
public static void main(String[] args) {
String[] A = {"abab", "ab", "abcd"};
System.out.println(findLCP(A)); // Output: ab
}
}
Wipro
|
2025-05-26
|
java
Q: A = {"abab", "ab", "abcd"}
output: ab
public class LongestCommonPrefix {
public static String findLCP(String[] strs) {
if (strs == null || strs.length == 0) return "";
String prefix = strs[0];
for (int i = 1; i < strs.length; i++) {
while (!strs[i].startsWith(prefix)) {
prefix = prefix.substring(0, prefix.length() - 1);
if (prefix.isEmpty()) return "";
}
}
return prefix;
}
public static void main(String[] args) {
String[] A = {"abab", "ab", "abcd"};
System.out.println(findLCP(A)); // Output: ab
}
}
Other
|
2025-05-26
|
java
Q: String s = "asd567ghj87hg987";
output
Numbers: [567, 87, 987]
Letters: [asd, ghj, hg]
Largest Number: 987
import java.util.regex.*;
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
String s = "asd567ghj87hg987";
// Extract number parts
List<Integer> numbers = Pattern.compile("\\d+")
.matcher(s)
.results()
.map(MatchResult::group)
.map(Integer::parseInt)
.collect(Collectors.toList());
// Extract letter parts
List<String> letters = Pattern.compile("[a-zA-Z]+")
.matcher(s)
.results()
.map(MatchResult::group)
.collect(Collectors.toList());
// Find the maximum number
int max = numbers.stream()
.mapToInt(Integer::intValue)
.max()
.orElseThrow(() -> new NoSuchElementException("No numbers found"));
// Print results
System.out.println("Numbers: " + numbers);
System.out.println("Letters: " + letters);
System.out.println("Largest Number: " + max);
}
}
Other
|
2025-05-26
|
java
Q: String s = "asd567ghj87hg987";
output: 567
import java.util.regex.*;
import java.util.*;
import java.util.stream.*;
public class Main {
public static void main(String[] args) {
String s = "asd567ghj87hg987";
// Create a Pattern to match digit sequences
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(s);
// Use a Stream to find all numbers and get the max
int max = pattern.matcher(s)
.results() // Stream<MatchResult>
.map(MatchResult::group) // Stream<String>
.mapToInt(Integer::parseInt) // IntStream
.max()
.orElseThrow(() -> new NoSuchElementException("No numbers found"));
System.out.println("Largest number: " + max);
}
}
Other
|
2025-05-26
|
java
Q: String s = "asd567ghj87hg987";
import java.util.regex.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
String s = "asd567ghj87hg987";
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher(s);
int max = Integer.MIN_VALUE;
while (matcher.find()) {
String numberStr = matcher.group();
int number = Integer.parseInt(numberStr);
if (number > max) {
max = number;
}
}
System.out.println("Largest number: " + max);
}
}
Other
|
2025-05-24
|
java
Q: String s ="My name is Mazhar";
output :yM eman si rahzaM
import java.util.*;
class Main {
public static void main(String[] args) {
String rev = new StringBuilder(s).toString();
String[] words = rev.split(" ");
StringBuilder result = new StringBuilder();
for(String word: words){
result.append(new StringBuilder(word).reverse().toString()).append(" ");
}
System.out.println("Output "+result);
}
}
Other
|
2025-05-21
|
java
Q: Find the prime number while enter input 10
output: 1 1 2 3 5 8
import java.util.*;
class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the input");
int n = input.nextInt();
int num1 = 0;
int num2 = 1;
for(int i=0;i<n;i++){
int next = num1+num2;
num1 = num2;
num2 = next;
if(num1<n){
System.out.print(num1 + " ");
}
}
}
}