|
| 1 | +package com.eazybytes.java22; |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.FileNotFoundException; |
| 5 | +import java.io.FileReader; |
| 6 | +import java.io.IOException; |
| 7 | +import java.util.Arrays; |
| 8 | +import java.util.List; |
| 9 | +import java.util.Map; |
| 10 | +import java.util.stream.Collectors; |
| 11 | + |
| 12 | +public class UnnamedVariables { |
| 13 | + |
| 14 | + public static void main(String[] args) { |
| 15 | + // Scenario 1 |
| 16 | + List<String> wordList = Arrays.asList("apple", "banana", "orange", "grape", "kiwi"); |
| 17 | + int totalWords = countWords(wordList); |
| 18 | + System.out.println(totalWords); |
| 19 | + |
| 20 | + // Scenario 2 |
| 21 | + List<String> fruits = Arrays.asList("apple", "banana", "orange"); |
| 22 | + Map<String, String> fruitMap = fruits.stream() |
| 23 | + .collect(Collectors.toMap(f -> f, _ -> "Fruit")); |
| 24 | + System.out.println(fruitMap); |
| 25 | + |
| 26 | + // Scenario 3 |
| 27 | + boolean isValid = convertAndDisplay("45"); |
| 28 | + |
| 29 | + // Scenario 4 |
| 30 | + executeIfFilePresent(); |
| 31 | + |
| 32 | + // Scenario 5 |
| 33 | + Point point = new Point(7, 3); |
| 34 | + if (point instanceof Point(int x, _)) { |
| 35 | + // Only use the 'x' property from the Point record |
| 36 | + System.out.printf("Point object with value of x: %d%n", x); |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + public static int countWords(Iterable<String> words) { |
| 41 | + int totalWords = 0; |
| 42 | + for (String _ : words) { |
| 43 | + totalWords++; |
| 44 | + } |
| 45 | + return totalWords; |
| 46 | + } |
| 47 | + |
| 48 | + public static boolean convertAndDisplay(String input) { |
| 49 | + boolean isValid; |
| 50 | + try{ |
| 51 | + int _ = Integer.parseInt(input); |
| 52 | + isValid = true; |
| 53 | + }catch (NumberFormatException _) { |
| 54 | + System.out.println("NumberFormatException due to invalid input: " + input); |
| 55 | + isValid = false; |
| 56 | + }catch (Exception _) { |
| 57 | + System.out.println("Exception due to invalid input: " + input); |
| 58 | + isValid = false; |
| 59 | + } |
| 60 | + return isValid; |
| 61 | + } |
| 62 | + |
| 63 | + public static void executeIfFilePresent() { |
| 64 | + String filePath = "example.txt"; |
| 65 | + try(BufferedReader _ = new BufferedReader(new FileReader(filePath));){ |
| 66 | + System.out.println("Executing some logic"); |
| 67 | + } catch (FileNotFoundException _) { |
| 68 | + System.out.println("FileNotFoundException"); |
| 69 | + } catch (IOException _) { |
| 70 | + System.out.println("IOException"); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | +} |
| 75 | + |
| 76 | +record Point(int x, int y) { } |
| 77 | + |
0 commit comments