Java.Java8.How can I get the average of all numbers?

✅ Example: Average of All Numbers in a Set

import java.util.Set;

public class AverageExample {
    public static void main(String[] args) {
        Set<Integer> numbers = Set.of(10, 20, 30, 40, 50);

        double average = numbers.stream()
                                .mapToInt(Integer::intValue)
                                .average()
                                .orElse(0.0); // fallback if set is empty

        System.out.println("Average: " + average);
    }
}

🔹 Output:

Average: 30.0
Continue reading →
Posted in Без рубрики | Comments Off on Java.Java8.How can I get the average of all numbers?

Java.Java8.How can I get the sum of all numbers in a set?

✅ Example: Sum of All Numbers in a Set

import java.util.Set;

public class SumOfSet {
    public static void main(String[] args) {
        Set<Integer> numbers = Set.of(10, 25, 7, 40, 18);

        int sum = numbers.stream()
                         .mapToInt(Integer::intValue) // convert to IntStream
                         .sum();                      // sum up the values

        System.out.println("Sum: " + sum);
    }
}

🔹 Output:

Sum: 100

✅ Breakdown

MethodDescription
stream()Turns the Set into a Stream
mapToInt()Converts Integer objects to primitives
sum()Sums all elements in the IntStream

🧠 Bonus: Using reduce()

If you want to practice reduce():

int sum = numbers.stream()
                 .reduce(0, Integer::sum);
Posted in Без рубрики | Comments Off on Java.Java8.How can I get the sum of all numbers in a set?

Java.Java8.How can I find the minimum number in a set?

To find the minimum number in a Set, you can use the min() method in a stream — just like you did with max().

✅ Example: Find Min in a Set

import java.util.Set;
import java.util.Comparator;

public class MinInSet {
    public static void main(String[] args) {
        Set<Integer> numbers = Set.of(10, 25, 7, 40, 18);

        numbers.stream()
               .min(Comparator.naturalOrder())
               .ifPresent(min -> System.out.println("Min: " + min));
    }
}

🔹 Output:

Min: 7

✅ Explanation

MethodPurpose
.stream()Turns the set into a stream
.min(...)Finds the minimum value
Comparator.naturalOrder()Compares using natural ordering
.ifPresent(...)Handles the Optional result safely
Posted in Без рубрики | Comments Off on Java.Java8.How can I find the minimum number in a set?

Java.Java8.How can I find the maximum number in a set?

👑 To find the maximum number in a Set using Java Streams, you can use the max() terminal method with a comparator.

✅ Example: Find Max in a Set

import java.util.Set;
import java.util.Comparator;

public class MaxInSet {
    public static void main(String[] args) {
        Set<Integer> numbers = Set.of(10, 25, 7, 40, 18);

        numbers.stream()
               .max(Comparator.naturalOrder())  // or just Comparator.comparingInt(i -> i)
               .ifPresent(max -> System.out.println("Max: " + max));
    }
}

🔹 Output:

Max: 40

✅ Explanation:

  • .stream() – converts the Set to a stream
  • .max(...) – finds the max using natural order
  • .ifPresent(...) – safely prints the result (since max() returns an Optional<T>)

🧠 Bonus: Use Collections.max() (alternative way)

int max = Collections.max(numbers);
System.out.println("Max: " + max);
Posted in Без рубрики | Comments Off on Java.Java8.How can I find the maximum number in a set?

Java.Java8.How can I display 10 random numbers in ascending order?

👌 To display 10 random numbers in ascending order, you can:

  1. Generate 10 random numbers,
  2. Sort them using sorted(),
  3. Print them using forEach().

✅ Example Using Random and Streams

import java.util.Random;
import java.util.stream.Stream;

public class SortedRandomNumbers {
    public static void main(String[] args) {
        Random random = new Random();

        Stream.generate(() -> random.nextInt(100)) // random numbers 0–99
              .limit(10)                           // get 10 numbers
              .sorted()                            // sort them
              .forEach(System.out::println);       // print
    }
}
Continue reading →
Posted in Без рубрики | Comments Off on Java.Java8.How can I display 10 random numbers in ascending order?

Java.Java8.How can I display the number of empty strings using the filter() method?

✅ Goal:

  • Use filter() to keep only empty strings.
  • Use count() to get the number of them.

🔹 Example:

import java.util.List;

public class EmptyStringCounter {
    public static void main(String[] args) {
        List<String> strings = List.of("hello", "", "world", "", "java", "");

        long count = strings.stream()
                            .filter(String::isEmpty)  // keep only empty strings
                            .count();                 // count them

        System.out.println("Number of empty strings: " + count);
    }
}

🔹 Output:

Number of empty strings: 3

✅ Breakdown:

  • filter(String::isEmpty): keeps only strings that are ""
  • count(): returns the total number of elements remaining after filtering
Posted in Без рубрики | Comments Off on Java.Java8.How can I display the number of empty strings using the filter() method?

Java.Java8.How can I display unique squares of numbers using the map() method?

✅ Goal:

  • Square each number in a list.
  • Remove duplicates (make them unique).
  • Print them using forEach().
Continue reading →
Posted in Без рубрики | Comments Off on Java.Java8.How can I display unique squares of numbers using the map() method?

Java.Java8.How can I display 10 random numbers using forEach()?

✅ Example using Stream.generate()

import java.util.Random;
import java.util.stream.Stream;

public class RandomExample {
    public static void main(String[] args) {
        Random random = new Random();

        Stream.generate(() -> random.nextInt(100)) // generate infinite stream of random ints (0–99)
              .limit(10)                           // take only the first 10
              .forEach(System.out::println);       // print each number
    }
}

🔹 Breakdown:

  • Stream.generate(...): creates an infinite stream
  • random.nextInt(100): generates a random number between 0 and 99
  • limit(10): keeps only the first 10
  • forEach(...): prints them one by one
Continue reading →
Posted in Без рубрики | Comments Off on Java.Java8.How can I display 10 random numbers using forEach()?

Java.Java8.What intermediate methods for working with streams do you know?

✅ Common Intermediate Stream Methods

Here’s a full list of the most important ones grouped by purpose:


🔹 1. Transformation

MethodDescription
map()Transforms each element
flatMap()Flattens nested streams
mapToInt(), mapToDouble(), mapToLong()Special for primitives
Continue reading →
Posted in Без рубрики | Comments Off on Java.Java8.What intermediate methods for working with streams do you know?

Java.Java8.What final methods for working with streams do you know?

🔹 1. Collecting Results

MethodDescription
collect()Accumulates elements into a collection (like List, Set, Map)
toArray()Converts the stream into an array

Example:

List<String> result = stream.collect(Collectors.toList());
Continue reading →
Posted in Без рубрики | Comments Off on Java.Java8.What final methods for working with streams do you know?