0% found this document useful (0 votes)
4 views10 pages

Interview Programs

The document contains multiple Java classes demonstrating various programming concepts such as counting characters, finding duplicates, and manipulating strings using Java 8 streams. Each class includes a main method that executes specific tasks, such as calculating the longest substring, removing duplicates, and reversing strings. Outputs for each class are provided as comments, illustrating the results of the operations performed.

Uploaded by

hunk065
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views10 pages

Interview Programs

The document contains multiple Java classes demonstrating various programming concepts such as counting characters, finding duplicates, and manipulating strings using Java 8 streams. Each class includes a main method that executes specific tasks, such as calculating the longest substring, removing duplicates, and reversing strings. Outputs for each class are provided as comments, illustrating the results of the operations performed.

Uploaded by

hunk065
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1 public class Capgemini1 {

2
3 public static void main(String[] args) {
4
5 String str = "Ramesh"; //count each char
6 Map<Character, Long> counts = [Link]()
7 .mapToObj(c -> (char) c)
8 .collect([Link](c -> c, [Link]()));
9 [Link](counts);
10 }
11 }
12 //Output: {a=1, R=1, s=1, e=1, h=1, m=1}
13 -----------------------------------------------------------------------------------------
14
15 public class Capgemini2 {
16
17 public static void main(String[] args) {
18 String st[]= {"Golang","array","Python"};
19 for(String s: st) {
20 // Frequency map: case-insensitive
21 Character findFirstChar = [Link]()
22 .mapToObj(c -> [Link]((char) c))
23 .collect([Link](
24 [Link](),
25 LinkedHashMap::new,
26 [Link]()
27 )).entrySet().stream().filter(c-> [Link]()==1)
28 .map(e->[Link]()).findFirst().orElse(null);
29 [Link](findFirstChar);
30 //[Link]() returns an IntStream of Unicode values (ASCII codes) of characters in the
string
31 //toLowerCase() is used only for counting, not for printing — so 'P' stays uppercase in
the output.
32 }
33 }
34
35 }
36 //Output: o y P
37 -----------------------------------------------------------------------------------------
-------------
38
39 public class CGI_LongestSubstringJava8 {
40 public static void main(String[] args) {
41 String s = "abcabcbb";
42 String result = longestSubstring(s);
43 [Link]("Longest substring: " + result);
44 [Link]("Length: " + [Link]());
45 }
46
47 public static String longestSubstring(String s) {
48 Map<Character, Integer> map = new HashMap<>();
49 int start = 0;
50 int maxLength = 0;
51 int maxStart = 0;
52
53 for (int end = 0; end < [Link](); end++) {
54 char currentChar = [Link](end);
55
56 // Check if character already exists in the map
57 if ([Link](currentChar) && [Link](currentChar) >= start) {
58 start = [Link](currentChar) + 1;
59 }
60
61 // Update the latest index of current character
62 [Link](currentChar, end);
63
64 // Update max length and starting index of the longest substring
65 if (end - start + 1 > maxLength) {
66 maxLength = end - start + 1;
67 maxStart = start;
68 }
69 }
70
71 return [Link](maxStart, maxStart + maxLength);
72 }
73 }
74 //Ouput: Longest substring: abc
75 Length: 3
76 -------------------------------------------------------------------------------------
77
78 public class ReflectionsInfoSystems {
79
80 public static void main(String[] args) {
81
82 int[] nums = {6, 9, 2, 1, 1, 8};
83 int target = 9;
84
85 List<List<Integer>> result = new ArrayList<>();
86 boolean[] used = new boolean[[Link]];
87
88 for (int i = 0; i < [Link]; i++) {
89 if (!used[i]) {
90 List<Integer> group = new ArrayList<>();
91 if (findGroup(nums, used, target, 0, group)) {
92 [Link](group);
93 }
94 }
95 }
96
97 [Link](result);
98 }
99
100 private static boolean findGroup(int[] nums, boolean[] used, int target, int start,
List<Integer> group) {
101 if (target == 0) return true;
102
103 for (int i = start; i < [Link]; i++) {
104 if (!used[i] && nums[i] <= target) {
105 used[i] = true;
106 [Link](nums[i]);
107
108 if (findGroup(nums, used, target - nums[i], i + 1, group)) {
109 return true;
110 }
111
112 used[i] = false;
113 [Link]([Link]() - 1);
114 }
115 }
116 return false;
117 }
118 }
119 // output: [[6, 2, 1], [9], [1, 8]]
120 -----------------------------------------------------------------------------------------
121
122 public class RemoveDuplicateCharFromString {
123
124 public static void main(String[] args) {
125
126 String input = "programming";
127
128 String result = [Link]()
129 .distinct()
130 .mapToObj(c -> [Link]((char) c))//converts the character into a
String
131 .collect([Link]());
132
133 [Link](result);
134 //output: progamin
135 }
136 }
137 -----------------------------------------------------------------------------------
138
139 public class ReverseEachWord {
140
141 public static void main(String[] args) {
142
143 String input = "Java is awesome";
144 String result = [Link]([Link](" "))
145 .map(w -> new StringBuilder(w).reverse())
146 .collect([Link](" "));
147
148 [Link](result);
149 }
150 }
151 //output: avaJ si emosewa
152 -----------------------------------------------------------------------
153
154 public class ReverseEachWord_Java7 {
155
156 public static void main(String[] args) {
157
158 String input = "Hello World Java";
159 String[] words = [Link](" ");
160
161 String result = "";
162
163 for (String word : words) {
164 for (int i = [Link]() - 1; i >= 0; i--) {
165 result += [Link](i);
166 }
167 result += " ";// this is print space between words
168 }
169
170 [Link]([Link]());
171 }
172 }
173 Ouput: olleH dlroW avaJ
174 ------------------------------------------------------------------------
175
176 public class CountDuplicateCharFromString {
177
178 public static void main(String[] args) {
179 String input = "Programming";
180
181 Map<Character, Long> countDuplicateChar = [Link]()
182 .chars()
183 .mapToObj(c -> (char) c)
184 .collect([Link](
185 [Link](),
186 [Link]()
187 ))
188 .entrySet()
189 .stream()
190 .filter(e -> [Link]() > 1)
191 .collect([Link]( [Link]::getKey,
192 [Link]::getValue));
193
194 [Link](countDuplicateChar);
195 }
196 }
197 output: {r=2, g=2, m=2}
198 ------------------------------------------------------------------------------
199
200 public class Capgemini {
201
202 public static void main(String[] args) {
203
204 List<Integer> numbers = [Link](1, 2, 3, 4);
205
206 int sum1 = [Link](0, 2).stream()//exclude 2
207 .mapToInt(Integer::intValue).sum(); // 1 + 2 = 3
208
209 int sum2 = [Link](2, 4).stream()//exclude 4
210 .mapToInt(Integer::intValue).sum(); // 3 + 4 = 7
211
212 int result = sum1 * sum2; // 3 * 7 = 21
213
214 [Link]("Result = " + result);
215
216 }
217 }
218 output: 21
219 ------------------------------------------------------------------------------------
220
221 public class FindDupStringFromArrayList {
222
223 public static void main(String[] args) {
224
225 List<String> li = [Link]("Bat","Cat","Apple","Lion","Apple","Kite");
226 // Approach-1
227 List<String> reuslt = [Link]().collect([Link]([Link]
(),[Link]()))
228 .entrySet().stream().filter(v->[Link]()>1)
229 .map(v->[Link]()).collect([Link]());
230
231 [Link]([Link]::println);
232
233
234 // Approach-2
235 List<String> duplicates = [Link]()
236 .filter(s -> [Link](li, s) > 1)
237 .distinct()
238 .collect([Link]());
239
240 [Link](duplicates);
241
242 // Count each String occurrence
243 Map<String, Long> count = [Link]()
244 .collect([Link]([Link](), [Link]
()));
245 [Link](count);
246
247 }
248 }
249 output: Apple
250 [Apple]
251 {Apple=2, Bat=1, Cat=1, Lion=1, Kite=1}
252 -----------------------------------------------------------------------------------------
------
253
254 public class CapgeminiFindDuplNum {
255
256 public static void main(String[] args) {
257
258 int[] arr = { 1, 2, 3, 4, 5, 4, 5 };
259
260 List<Integer> duplicates = [Link](arr).boxed()
261 .collect([Link](n -> n, [Link]()))
262 .entrySet().stream()
263 .filter(v -> [Link]() > 1)
264 .map(k->[Link]())
265 .collect([Link]());
266
267 [Link](duplicates);
268 }
269 }
270 output: [4, 5]
271 -----------------------------------------------------------------------------------------
-----
272
273 List<Employee2> empList = Arrays
274 .asList(new Employee2("Arun", [Link]("Java", "C++")),
275 new Employee2("Kiran", [Link]("Python", "Angular")),
276 new Employee2("Shaan", [Link]("Java", "C++")));
277
278
279 // Using Java 8 streams to get unique skills with Set
280 Set<String> uniqueSkills = [Link]()
281 .flatMap(emp -> [Link]().stream()) // flatten list of skills
282 .collect([Link]()); // collect as Set to get unique skills
283 [Link]("Unique Skills: " + uniqueSkills);
284
285 // Using Java 8 streams to get unique skills with List
286 List<String> skillsWithList = [Link]()
287 .flatMap(emp -> [Link]().stream()).distinct() // flatten list of
skills
288 .collect([Link]()); // collect as Set to get unique skills
289
290 [Link]("Unique Skills: " + skillsWithList);
291
292 }
293 }
294 output: Unique Skills: [Java, C++, Angular, Python]
295 Unique Skills: [Java, C++, Python, Angular]
296
297 -----------------------------------------------------------------------------
298
299 public class Atos {
300
301 public static void main(String[] args) {
302
303 List<Integer> li = [Link](17, 12, 34, 98, 11, 1, 18);
304
305 int sum = [Link]().filter(i-> i%2 !=0).filter(n->[Link](n)
306 .startsWith("1")).reduce(0, (a,b)->a+b).intValue();
307
308 [Link](sum+" ");// Out put: Sum = 17 + 11 + 1 = 29
309
310 }
311 }
312 output: 29
313 -------------------------------------------------------------------------------
314
315 public class BirlaSoftFirstNonDuplChars {
316
317 public static void main(String[] args) {
318
319 String str="swiss";
320 Character firstNonduplicateChar = [Link]().mapToObj(c -> (char) c)
321 .collect([Link]([Link](),LinkedHashMap::new,Collectors.
counting()))
322 .entrySet().stream()
323 .filter(v -> [Link]() == 1)//Filter characters that appear only once
324 //.map([Link]::getKey)// this is using method reference.
325 .map(k->[Link]())//Extract the character (key)
326 .findFirst().get();
327 [Link](firstNonduplicateChar);
328 }
329 }
330 output: w
331 -----------------------------------------------------------------------------------
332
333 public class FindSecondHighestNum {
334
335 public static void main(String[] args) {
336
337 List<Integer> list = [Link](10, 20, 30, 40);
338
339 int[] ar={1,2,3,4,12,1,3};
340
341 Integer secondHighest =
342 [Link]()
343 .sorted([Link]())
344 .skip(1)
345 .findFirst()
346 .get();
347
348 [Link](secondHighest);
349
350 List<Integer> uniqueVal = [Link](ar).boxed()
351 .collect([Link]([Link](),[Link]()))
352 .entrySet().stream().filter(v->[Link]()==1)
353 .map(k->[Link]()).collect([Link]());
354
355 [Link](uniqueVal);
356 }
357 }
358 output: 30
359 [2, 4, 12]
360 ---------------------------------------------------------------------------------
361
362 public class HighestPaidByDept {
363
364 public static void main(String[] args) {
365 List<Employee4> employees = [Link](
366 new Employee4(1,"John", "HR", 50000),
367 new Employee4(2,"Jane", "IT", 70000),
368 new Employee4(3,"Mike", "IT", 80000),
369 new Employee4(4,"Sara", "Finance", 60000),
370 new Employee4(5,"Paul", "HR", 55000));
371
372 Map<String, Optional<Employee4>> collect = [Link]()
373 .collect([Link](
374 Employee4::getDepartment,
375 [Link]([Link](Employee4::getSalary))
376 ));
377
378 [Link](collect);
379
380 }
381 }
382 output:
383 {Finance=Optional[Employee4 [id=4, name=Sara, department=Finance, salary=60000.0]],
384 HR=Optional[Employee4 [id=5, name=Paul, department=HR, salary=55000.0]],
385 IT=Optional[Employee4 [id=3, name=Mike, department=IT, salary=80000.0]]}
386 ---------------------------------------------------------------------------------------
387
388 public class ReverseString {
389
390 public static void main(String[] args) {
391
392 String input = "hello";
393
394 String reversed = [Link](0, [Link]())
395 .mapToObj(i -> [Link]([Link]() - 1 - i))
396 .map(String::valueOf)
397 .collect([Link]());
398
399 [Link](reversed);
400 }
401 }
402 output: olleh
403 ----------------------------------------------------------------------------------
404
405 public class FindDupStringFromArrayList {
406
407 public static void main(String[] args) {
408
409 List<String> li = [Link]("Bat","Cat","Apple","Lion","Apple","Kite","Cat");
410 // Approach-1
411 List<String> reuslt = [Link]()
412 .collect([Link]([Link](),[Link]()))
413 .entrySet().stream().filter(v->[Link]()>1)
414 .map(v->[Link]()).collect([Link]());
415
416 [Link](reuslt);
417
418 output: [Apple, Cat]
419 --------------------------------------------------------------------------------------
420
421 public class SortArray {
422
423 public static int sortArrayElements(int arr[]) {
424
425 if (arr == null || [Link] <= 1) return 0;
426
427 int len = [Link];
428 int temp = 0;
429
430 int result = 0;
431
432 for (int i = 0; i < len; i++) {
433
434 for (int j = 0; j <= i; j++) {
435 if (arr[i] <= arr[j]) { // if (arr[i] >= arr[j]) Code to Sort in
Descending Order
436 temp = arr[i];
437 arr[i] = arr[j];
438 arr[j] = temp;
439 }
440
441 }
442 }
443 [Link](arr).forEach((n)->[Link](n+" "));
444 return result;
445 }
446
447 public static void main(String[] args) {
448
449 int arr[] = { 10, 6, 3, 9, 2, 7, 11, 1, 8, 4, 5 };
450
451 sortArrayElements(arr);
452 }
453 }
454 output: 1 2 3 4 5 6 7 8 9 10 11
455 -------------------------------------------------------------------------------
456
457 public class PalindromeRearrangementJava8 {
458
459 public static boolean canFormPalindrome(String s) {
460 Map<Character, Long> freqMap =
461 [Link]()
462 .mapToObj(c -> (char) c)
463 .collect([Link](
464 [Link](),
465 [Link]()
466 ));
467
468 long oddCount = [Link]()
469 .stream()
470 .filter(count -> count % 2 != 0)
471 .count();
472
473 return oddCount <= 1;
474 }
475
476 public static void main(String[] args) {
477 [Link](canFormPalindrome("bangalore")); // false
478 [Link](canFormPalindrome("abdybayd")); // true
479 }
480 }
481 ----------------------------------------------------------------------------------------
482
483 public class PalindromeRearrangementJava7 {
484
485 public static boolean canFormPalindrome(String s) {
486 Map<Character, Integer> freqMap = new HashMap<>();
487
488 for (char c : [Link]()) {
489 [Link](c, [Link](c, 0) + 1);
490 }
491
492 int oddCount = 0;
493 for (int count : [Link]()) {
494 if (count % 2 != 0) {
495 oddCount++;
496 if (oddCount > 1) {
497 return false;
498 }
499 }
500 }
501 return true;
502 }
503
504 public static void main(String[] args) {
505 [Link](canFormPalindrome("bangalore")); // false
506 [Link](canFormPalindrome("abdybayd")); // true
507 }
508 }
509 ----------------------------------------------------------------------------------
510 public class FindDuplicateStringAndIntegerFromList {
511
512 public static void main(String[] args) {
513
514 List<String> list = [Link]("A", "B", "A", "C", "B", "D");
515
516
517
518 List<String> duplicateElements = [Link]()
519 .collect([Link]([Link](),LinkedHashMap::new, Collectors
.counting()))
520 .entrySet().stream()
521 .filter(v->[Link]()>1)
522 .map(k->[Link]()).collect([Link]());
523 [Link]("Print duplicates : "+duplicateElements);// Output: [A, B]
524 }
525 }
526 -----------------------------------------------------------------------------------------
-----------
527
528 public class FindNumberBasedOnConditionFromList {
529
530 public static void main(String[] args) {
531
532 List<Integer> list1 = [Link](10, 7, 8, 11, 13, 15);
533
534 List<Integer> result = [Link]().filter(i->i > 10).collect([Link]
());
535 [Link]("Print greater than 10 : "+result);
536
537 }
538 }
539 // Output: [11, 13, 15]
540 -----------------------------------------------------------------------------------------
-------------
541
542 public class FindUniqueCharFromString {
543
544 public static void main(String[] args) {
545 String st ="TEST";
546
547 String value = [Link]().mapToObj(c-> (char) c)
548 .collect([Link]([Link](),LinkedHashMap::new, Collectors
.counting()))
549 .entrySet().stream()
550 .filter(v->[Link]()==1)
551 .map(String::valueOf).collect([Link]());
552 [Link]("Find non-repeated char : "+value);
553 }
554 }
555 // Output: ES
556 -----------------------------------------------------------------------------------------
----
557
558 public class TopThreeDoubles {
559
560 public static void main(String[] args) {
561
562 List<Double> list = [Link](10.5, 3.2, 25.7, 18.4, 7.9, 25.7);
563
564 List<Double> top3 = [Link]().distinct()
565 .sorted([Link]())
566 .limit(3).collect([Link]());
567 [Link](top3+" ");
568 }
569 }
570
571 Ouput: [25.7, 18.4, 10.5]
572 -----------------------------------------------------------------------------------------
-
573
574 public class GroupAllStringsBasedOnTheirLength {
575
576 public static void main(String[] args) {
577
578 // This Emphasis question
579 String[] words = {"apple","banana","mango","mississippi"
580 ,"chocolate","committee","engineering"};
581
582 Map<Integer, List<String>> groupedByLength = [Link](words)
583 .collect([Link](String::length));
584
585 [Link](groupedByLength);
586 }
587 }
588 Output: {5=[apple, mango], 6=[banana], 9=[chocolate, committee], 11=[mississippi,
engineering]}
589 -----------------------------------------------------------------------------------------
-----------
590
591 public class HCLMain {
592 public static void main(String[] args) {
593
594 List<Student> studList = new ArrayList<>();
595
596 [Link](new Student(1, "Alice"));
597 [Link](new Student(2, "Bob"));
598 [Link](new Student(1, "Alice")); // duplicate
599
600 // Use a LinkedHashSet to maintain order and remove duplicates
601 Set<Student> set = new LinkedHashSet<>(studList);
602 [Link]();
603 [Link](set);
604
605 [Link]("Output: Using LinkedHashSet");
606 for (Student s : studList) {
607 [Link]( [Link]()+ " - " +[Link]());
608 }
609
610 // Using Java8. in this case your student class must implement equals() and
hashCode()
611 //otherwise you can't able to get distinct object.
612 List<Student> distinctPeople = [Link]()
613 .distinct()
614 .collect([Link]());
615
616 [Link]("Output: Using streams");
617 [Link](p -> [Link]([Link]() + " - " + [Link]()));
618 }
619 }
620 Output: Using LinkedHashSet
621 1 - Alice
622 2 - Bob
623
624 Output: Using streams
625 Alice - 1
626 Bob - 2
627 --------------------------------------------------------------------------------------
628
629 public class ProductSortingExample {
630 public static void main(String[] args) {
631 List<Product> products = [Link](
632 new Product("Laptop", 1200.0, 4.5),
633 new Product("Smartphone", 800.0, 4.8),
634 new Product("Headphones", 150.0, 4.2),
635 new Product("Monitor", 300.0, 4.6),
636 new Product("Keyboard", 150.0, 4.5),
637 new Product("Mouse", 50.0, 4.1)
638 );
639 // Sort by price (asc), rating (desc), name (asc)
640
641 List<Product> sortedProducts = [Link]()
642 .sorted([Link](Product::getPrice)
643 .thenComparing([Link](Product::getRating).reversed
())
644 .thenComparing(Product::getName));
645 }
646 }
647 1. Price → Ascending
648 2. Rating → Descending (for same price)
649 3. Name → Ascending (if price and rating are same)
650
651 Ouput:
652 Mouse - $50.0 - Rating: 4.1
653 Keyboard - $150.0 - Rating: 4.5
654 Headphones - $150.0 - Rating: 4.2
655 Monitor - $300.0 - Rating: 4.6
656 Smartphone - $800.0 - Rating: 4.8
657 Laptop - $1200.0 - Rating: 4.5
658
659
660
661

You might also like