JetBrains Academy: List - Kamil-Jankowski/Learning-JAVA GitHub Wiki

JetBrains Academy: List

Greek letters:

Given a list of GreekLetter objects.

Print each element from this list on a new line.

Invoke the toString method to get the string representation of an object.

import java.util.*;

public class Main {

    public static void main(String[] args) {
        List<GreekLetter> letterList = new ArrayList<>();

        letterList.add(new GreekLetter("Gamma",  3));
        letterList.add(new GreekLetter("Omega", 24));
        letterList.add(new GreekLetter("Alpha",  1));

        for (GreekLetter letter : letterList){
            System.out.println(letter.toString());
        }
    }

    static class GreekLetter {

        private String letter;
        private Integer position;

        public GreekLetter(String letter, Integer position) {
            this.letter = letter;
            this.position = position;
        }

        @Override
        public String toString() {
            return "{" +
                    "letter='" + letter + '\'' +
                    ", position=" + position +
                    '}';
        }
    }
}

Filtering the list:

Write a program that reads the list of integer number separated by spaces from the standard input and then remove all numbers with even indexes (0, 2, 4, and so on). After, the program should output the result sequence in the reverse order.

import java.util.*;

class Main {
    public static void main(String[] args) {
        final Scanner scanner = new Scanner(System.in);
        List<Integer> inputList = new ArrayList<>();
        List<Integer> outputList = new ArrayList<>();

        while(scanner.hasNext()){
            inputList.add(scanner.nextInt());
        }

        for (int i = inputList.size()-1; i >= 0; i--){
            if (i % 2 == 1){      // checking if it is even number (%2==0), here ==1 because of loop definition with "-1"
                outputList.add(inputList.get(i));
                System.out.print(inputList.get(i) + " ");
            }
        }
    }
}

The longest string in the list:

Inside the given method you should:

  1. find the longest string in the list
  2. replace all list items with the found string
import java.util.*;

public class Main {

    static void changeList(List<String> list){
        int maxLength = Integer.MIN_VALUE;
        String longWord = "";

        for (String word : list){
            if (word.length() > maxLength){
                maxLength = word.length();
                longWord = word;
            }
        }

        for (int i = 0; i < list.size(); i++){
            list.set(i, longWord);
        }
    }

    /* Do not change code below */
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        List<String> lst = Arrays.asList(s.split(" "));
        changeList(lst);
        lst.forEach(e -> System.out.print(e + " "));
    }
}

Split a list into sublists:

Implement a method for splitting (partitioning) a generic list into sublists. The methods takes two arguments: a generic list and a size of sublists. The specified size of sublists can be greater than the size of the given list.

Each sublist except the last one must have the specified size. The last sublist can have smaller number of elements.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;

class ListUtils {

    /**
     * It splits the passed list into a sequence of sublists with a predefined size 
     */
    public static <T> List<List<T>> splitListIntoSubLists(List<T> list, int subListSize) {
        List<List<T>> sublists = new ArrayList<>();

        for (int i = 0; i < list.size();){
            if (i+subListSize < list.size()){
                sublists.add(list.subList(i, i+subListSize));
            } else {
                sublists.add(list.subList(i, list.size()));
            }
            i += subListSize;
        }
        
        return sublists;
    }
}

/* Please, do not modify code in this class */
public class Main {
    public static void main(String[] args) {
        final Scanner scanner = new Scanner(System.in);

        final String[] values = scanner.nextLine().split("\\s+");

        final List<Integer> list = Arrays.asList(values).stream()
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        final int subListSize = Integer.parseInt(scanner.nextLine());

        final List<List<Integer>> subLists = ListUtils.splitListIntoSubLists(list, subListSize);

        subLists.forEach(subList -> {
            final String representation = subList.stream().map(Object::toString).collect(Collectors.joining(" "));
            System.out.println(representation);
        });
    }
}

Check the value occurs:

Implement a method that takes an integer value and two lists of numbers. It must check the value occurs the same number of times in both sequences.

In the following input example, the first line contains the value, the second line is one list, the third line is another list. All numbers are separated by whitespaces.

public static boolean checkTheSameNumberOfTimes(int elem, List<Integer> list1, List<Integer> list2) {
    int counterList1 = 0;
    int counterList2 = 0;
    for (Integer num : list1){
        if(num == elem){
            counterList1++;
        }
    }

    for (Integer num : list2){
        if(num == elem){
            counterList2++;
        }
    }

    return counterList1 == counterList2;
}

Companies:

Given a sequence of strings separated by spaces. Read the sequence from the standard input and store all strings to the list. Output the list to the standard output using System.out.println(yourList). The order of elements must be the same as in the input.

import java.util.*;

class Main {
    public static void main(String[] args) {
        final Scanner scanner = new Scanner(System.in);
        List<String> companies = List.of(scanner.nextLine().split(" "));
        System.out.println(companies);
    }
}

Backward indexes:

Implement a method that returns an element by the specified index from a list. The method must return elements by a regular and a backward index.

In the regular order, elements have indexes 0, 1, 2, ..., n - 1. In the backward order, the same elements have indexes -n, -n + 1, ..., -2, -1; where n is the size of a list.

If the specified index is out of bounds, the method must throw the standard IndexOutOfBoundsException.

import java.util.*;
import java.util.stream.Collectors;

public class Main {

    public static <T> T getElementByIndex(List<T> lst, int index) {
        if (index >= 0){
            return lst.get(index);
        } else {
            return lst.get(lst.size()+index);
        }
    }

    /* Do not change code below */
    public static void main(String[] args) {

        final Scanner scanner = new Scanner(System.in);

        final List<String> values = Arrays
                .stream(scanner.nextLine().split("\\s+"))
                .collect(Collectors.toList());

        final int index = Integer.parseInt(scanner.nextLine());

        try {
            String element = getElementByIndex(values, index);
            System.out.println(element);
        } catch (IndexOutOfBoundsException e) {
            System.out.println("Exception");
        }
    }
}

⚠️ **GitHub.com Fallback** ⚠️