Posts

Showing posts from July, 2024

Basics Of sample Collection

 // Online Java Compiler // Use this editor to write, compile and run your Java code online import java.util.*; class Main {     public static void main(String[] args) {              }     void sample1() {           List<String> games = new ArrayList<>();         games.add("Batminton");         games.add("Cricket");         games.add("Batminton");         games.add("Football");         System.out.println(games);                  Set<String> favouriteGames = new HashSet<>(games);         System.out.println(favouriteGames);      }    void convertArrayToList(int[] integers) {     System.out.println(Arrays.asList(integers)); }

Java Program to Calculate Total Income from a Collection of Room Objects

import java.util.*; class Main {     public static void main(String[] args) {        Room a = new Room("Delux", "enSuite", 4, 550);        Room b = new Room("Single", "Single", 1, 150);        Room c = new Room("Double", "Double", 2, 250);        Room d = new Room("Premier", "Premier", 4, 550);        Collection<Room> rooms = List.of(a, b, c, d);        System.out.println(calculateTotalIncome(rooms));     }     static double calculateTotalIncome(Collection<Room> rooms) {         return rooms.stream()         .mapToDouble(r -> r.getRate())   // .mapToDouble(Room::getRate)         .sum();     } } class Room {     String name;     String type;     int capacity;     double rate;    Room(String name, ...

Implement an immutable collection holder

  To implement an immutable collection holder, you need to ensure that the list of strings it holds cannot be modified after it is assigned. This can be done by creating an unmodifiable copy of the list in the constructor and returning an unmodifiable view of the list in the getter method. Using Collections.unmodifiableList is a common way to achieve this in Java. import java.util.List; import java.util.ArrayList; import java.util.Collections; public class Main {     public static void main(String[] args) {         List<String> list = Arrays.asList("apple", "banana", "cherry");         ImmutableCollectionHolder holder = Answer.createImmutableCollectionHolder(list);         System.out.println("Immutable list: " + holder.getItems());         // Try to modify the list through the getter         try {             holder.getItems().add("date"...

Filter and sort with a stream

 A method filters a list of Item objects based on a maximum price and then sorts the filtered items by price. Here's a summary of what the method does: Filter : It filters the items where the price is less than maxPrice . Sort : It sorts the filtered items by their price in ascending order. Collect : It collects the sorted items into a list. Here is the code with comments and a main method added for testing: import java.util.List; import java.util.stream.Collectors; class Answer {     // Change these boolean values to control whether you see     // the expected answer and/or hints.     static boolean showExpectedResult = true;     static boolean showHints = false;     // Filter and sort the items array.     static List<Item> getFilteredData(List<Item> items, float maxPrice) {         return items.stream()                     .filter(item -...

Sort a list with a lambda expression

   The Java code snippet shows a class   Answer   with a method   sortList   that sorts a list of   Item   objects based on their price using a lambda expression.  Here's the full code with some explanations and a test example added: import java.util.ArrayList; import java.util.List; class Answer {     // Change these boolean values to control whether you see     // the expected answer and/or hints.     static boolean showExpectedResult = false;     static boolean showHints = false;     // Return the largest number in the 'numbers' array.     static List<Item> sortList(List<Item> items) {         List<Item> result = new ArrayList<>(items);         // Sort the result list using a lambda expression.         result.sort((a, b) -> Float.compare(a.getPrice(), b.getPrice()));         ...

Do Math With Lambda

To create a map of mathematical operations using lambda expressions in Java, you need to define BiFunction instances for each operation and use these to populate the results map. Here is the completed code: import java.util.HashMap; import java.util.Map; import java.util.function.BiFunction; class Answer {     // Change these boolean values to control whether you see     // the expected answer and/or hints     static boolean showExpectedResult = false;     static boolean showHints = false;     // Create constants representing the four available math functions     public static final String ADD = "ADD";     public static final String SUBTRACT = "SUBTRACT";     public static final String MULTIPLY = "MULTIPLY";     public static final String DIVIDE = "DIVIDE";     // Do mathematical calculations using lambda expressions     public static Map<String, Float> calculate(float va...

Inspect a collection

Calculate the cart total  import java.util.List; import java.util.concurrent.atomic.AtomicReference; public class Main {     public static void main(String[] args) {         List<Item> items = List.of(             new Item("Item1", 10.0f, 2),             new Item("Item2", 5.0f, 4),             new Item("Item3", 20.0f, 1)         );         float total = getCartTotal(items);         System.out.println("Cart Total: " + total);  // Output: Cart Total: 60.0     }     static float getCartTotal(List<Item> items) {         AtomicReference<Float> total = new AtomicReference<>(0.0f);         items.forEach(item -> {             total.updateAndGet(v -> v + item.getQuantity() * item.getPrice())...

Transform values with a stream

The goal is to transform an array of numbers into a comma-delimited string using functional programming. The code snippet you provided has a minor issue: String.join(",", strings[0]) is incorrect because it tries to join a single element ( strings[0] ) rather than all elements in the strings array. Here's the corrected code for the transformValues method: import java.util.Arrays; class Answer {     // Change these boolean values to control whether you see      // the expected answer and/or hints.     static boolean showExpectedResult = true;     static boolean showHints = true;     // Transform an array of numbers into a comma-delimited list     // using functional programming.     static String transformValues(int[] numbers) {         // Convert the int array to a stream of integers         // Map each integer to its String representation         // ...

Unique ID Generator

 import java.security.SecureRandom; public class IdGenerator {     private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";     private static final int ID_LENGTH = 12;     private static final SecureRandom RANDOM = new SecureRandom();     public static String generateUniqueUserId() {         StringBuilder userId = new StringBuilder(ID_LENGTH);         for (int i = 0; i < ID_LENGTH; i++) {             userId.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length())));         }         return userId.toString();     } }