# Code Examples #1

In 
Published 2024-02-03

# Narrowing casting (down casting)

long x = 7;
int y = (int) x;

# String - Integer - int conversion

Integer integerNumber = 10;

//Integer to String
String strNumber = integerNumber.toString();

//Integer to int - automatic unboxing
int intNumber = integerNumber;

//String to Integer
Integer integerNumber2 = Integer.valueOf(strNumber);

//String to int
int intNumber2 = Integer.parseInt(strNumber);

//int to Integer - automatic boxing
Integer integerNumber1 = intNumber;

//int to String
String strNumber1 = String.valueOf(intNumber2);

# Find closer value

Problem:

  • read from keyboard a string containing integers (we have one or more spaces between them)
  • read another integer from keyboard ("val1")
  • find a negative value which is closer to "val1". If there are no negative values return "0".
Scanner sc = new Scanner(System.in);

String line = sc.nextLine();
int val1 = sc.nextInt();

Integer returnedValue = 0;

List<Integer> negativeNumberList = Stream.of(line.split("\\s"))
        .map(String::trim)
        .filter(it -> it.length() > 0)
        .map(Integer::valueOf)
        .filter(it -> it < 0)
        .sorted(Comparator.reverseOrder()).toList();

if (negativeNumberList.size() > 0) {

    Integer[] negativeNumberArray = new Integer[negativeNumberList.size()];
    negativeNumberList.toArray(negativeNumberArray);

    Integer[] negativeNumberArray2 = new Integer[negativeNumberList.size()];

    for (int i = 0; i<negativeNumberArray.length; i++){
        negativeNumberArray2[i] = Math.abs(negativeNumberArray[i]- val1);
    }

    //Find the min value from an array
    int minValFronArray = Arrays.stream(negativeNumberArray2)
            .reduce(Integer::min)
            .get();
    
    //Find the position in array having this value
    for (int i = 0; i<negativeNumberArray2.length; i++){
        if (negativeNumberArray2[i] == minValFronArray) {
            returnedValue = negativeNumberArray[i];
            break;
        }
    }
}

System.out.println("returnedValue = " + returnedValue);

# Array <-> Collection <-> Array + iterate Array

// Create an Array
String[] strArray1 = new String[]{"Audi", "Peugeot", "Fiat", "Dacia"};

// Sort and create a Collection from Array
Collection<String> stringList = Stream.of(strArray1)
        .sorted(Comparator.reverseOrder()).toList();

// Create a new Array from the Collection
String[] strArray2 = new String[stringList.size()];
stringList.toArray(strArray2);

// Show the content of the Array 
Arrays.stream(strArray2).forEach(System.out::println);

# Sorting array

int[] array1 = {8, -2, -9, 50, 10, 20, -10};

// Sort of the Array
Arrays.sort(array1);

// Print the Array
Arrays.stream(array1).forEach(System.out::println);

# Two-dimensional array

syntax:

int[][] array = new int[rows][columns];
int[][] array = {{1, 2, 3}, {4, 1, 6}, {7, 8, 9}, {1, 1, 9}};

Arrays.stream(array).forEach(
        it -> {
            for(int i = 0; i<3; i++) {
                System.out.print(it[i]);
                System.out.print(" ");
            }
            System.out.println();
        }
);

// The length is 4 in this case
System.out.println("array.length="+array.length);

// Iterate through a 2-dimensional array
for (int i=0; i<array.length; i++){
    for(int j = 0; j<3; j++) {
        System.out.print(array[i][j]);
        System.out.print(" ");
    }
    System.out.println();
}

# For loop with step

for (int i=0; i<=10; i+=3)
    System.out.println("i="+i);

The result is :

i=0
i=3
i=6
i=9

# Grouping names by length

String names = "Adams Paul Dan Elena Emma Brown Emanuil";

Map<Integer, List<String>> namesMap = Arrays.stream(names.split(" ")).toList()
        .stream()
        .collect(
                Collectors.groupingBy(String::length)
        );

// forEach in Maps
namesMap.forEach( (val1, val2) -> {
    System.out.print(val1);
    System.out.print(" : ");
    System.out.print(val2);
    System.out.println("");
});

# Counting words in a string

List<String> items =
        Arrays.asList("Dacia", "Nissan", "Peugeot", "Nissan", "Dacia", "Peugeot", "Nissan");

Map<String, Long> carMap =
        items.stream().collect(
                Collectors.groupingBy(
                        Function.identity(), Collectors.counting()
                )
        );

carMap.forEach( (val1, val2) -> {
    System.out.print(val1);
    System.out.print(" : ");
    System.out.print(val2);
    System.out.println("");
});