K
K
KB202017-08-08 22:07:53
Java
KB20, 2017-08-08 22:07:53

Create a collection A and insert the elements of the sequence into it in an arbitrary order?

Guys, I'm new to java, they gave the task
It is necessary to do certain transformations with the data, using the correct collections and algorithms from the Java Collection Framework
I. Generate 1,000,000 consecutive integers
II. Create a collection A and insert the elements of the sequence into it in any order
III. Show that the order is arbitrary
IV. Write a check that all elements in a given collection A are unique (prove this in some way)
V. Find the minimum element in a given sequence
VI. Remove all odd elements from sequence
VII. Find the penultimate element
I created an ArrayList array, added a million numbers to it, tried to display it on the screen, everything is fine. Then I came to create a collection. I don’t understand which one to take (I suspect that HashSet), how to create, either in this class, or a method is needed. If so, which one. help me please

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gleendo, 2017-08-08
@KB20

// Возможно не лучшее решение, но это первое что пришло в голову, а более лучшее решение обдумывать не хочется.
import java.util.*;

public class App {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList(); // Создание коллекции

        for (int i = 0; i < 1000000; i++) { // Заполнение коллекции последовательностью чисел от 0 до 1000000
            list.add(i);
        }

        Collections.shuffle(list); // организация произвольного порядка

        for (int i = 0; i < 10; i++) {
            System.out.println(list.get(i) + " "); // Показываем что порядок произвольный, выводя первые 10 чисел к примеру
        }

        Map<Integer, Boolean> map = new HashMap<>();

        for (int i = 0; i < list.size(); i++) {
            map.put(list.get(i), true); // Map всегда содержит только уникальные ключи
        }

        System.out.println(list.size() == map.size()); // Если размеры равны то это значит что в исходной коллекции элементы были уникальны

        list.sort(new Comparator<Integer>() {
            @Override
            public int compare(Integer a, Integer b) {
                return a - b;
            }
        });

        System.out.println("Минимальный элемент: " + list.get(0));
        System.out.println("Предпоследний по величине элемент: " + list.get(list.size() - 2));

        ArrayList<Integer> alist = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) % 2 == 0) {
                alist.add(list.get(i)); // Сохраняем только четные числа
            }
        }

        list = null;

        for (int i = 0; i < alist.size() / 1000; i++) { // первые 1000 элементов
            System.out.println(alist.get(i) + " "); // Выводим последовательность четных чисел
        }
    }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question