Java course experiment - Experiment 6_ Collection class

Posted by Zaid on Wed, 09 Feb 2022 07:38:05 +0100

catalogue

1,

2,

3,

4,

5,

6,

7,

8,

1,

Add the following data: "hello", 123, 6.9, "hello", "hello", StringBuffer s=new StringBuffer("abc"); Add s in an ArrayList object and output the result.

• practice modifying elements, getting elements, and printouts.

• find the element "hello".

• delete the specified element "hello".

• replace element 123 with 1000.

import java.util.*;

public class SixDemo {
    public static void main(String[] args) {
        ArrayList list1 = new ArrayList();
        StringBuffer s = new StringBuffer("abc");
        list1.add("hello");
        list1.add(123);
        list1.add(6.9);
        list1.add("");
        list1.add("Hello");
        list1.add(s);
        System.out.println("Print original list---");
        System.out.println(list1);

        System.out.println("Modify the element with subscript 2 and obtain the element with subscript 2---");
        list1.set(2, 456);
        System.out.println("Element with subscript 2:" + list1.get(2));
        System.out.println("Modified list:" + list1);
        System.out.println("Find element hello Index of:" + list1.indexOf("hello"));
        System.out.println("delete hello element:" + list1.remove("hello"));

        Collections.replaceAll(list1, 123, 1000);
        //Note that all 123 in list1 are replaced with 1000

        System.out.println("Delete element hello And replace 123 with 1000---");
        System.out.println(list1);
    }
}

Operation screenshot:

2,

Use the ArrayList collection, add 10 different elements to it, and iterate through the collection using Iterator. Tips:

• use the add() method to add elements to the ArrayList collection.

• call the iterator() method of the set to obtain the Iterator object, and call the hasNext() and next() methods of the Iterator to iterate over all elements in the set.

• find the elements entered by the keyboard.

• delete duplicate elements.

import java.util.*;

public class SixDemo {
    public static void main(String[] args) {
        ArrayList<Integer> list = new ArrayList();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(56);
        list.add(4);
        list.add(7);
        list.add(8);
        list.add(9);
        Iterator it = list.iterator();

        //foreach loops are also called enhanced for loops
//        for (Integer ig : list) {
//            System.out.println(ig);
//        }

        //Iterator iterator traversal
        while (it.hasNext()) {
            Object obj = it.next();
            System.out.println(obj);
        }

        //Find elements entered by keyboard
        System.out.println("Please enter the element to find:");
        Scanner sc = new Scanner(System.in);
        int i = sc.nextInt();
        if (list.indexOf(i) != -1) System.out.println("The element is in list The location in the collection is:" + list.indexOf(i));
        else System.out.println("The element does not exist!");

        //Delete duplicate elements
        System.out.println("delete list Duplicate elements in the collection;");

        for (int j = 0; j < list.size(); j ++ )
            for (int t = j + 1; t > j && t < list.size(); t ++ )
                if (list.get(j).equals(list.get(t))) list.remove(t);

        System.out.println(list);
    }
}

Operation screenshot:

3,

Remove the duplicate values of custom objects in the collection (such as the Person class, whose attributes include name and age) (the member variable values of the objects are the same).

Idea:

First, store the instance objects of these Person classes into the ArrayList set, which contains duplicate values (that is, the values of all variables of the instance are the same, which is called repetition). Then, traverse the list set and store all elements into the HashSet set set. At this time, the task of de duplication is completed.

It should be noted that when storing a String in the HashSet set set, the String class has rewritten the equals () and hashcode () methods. You only need to store elements to remove duplication. However, for custom objects such as Person class instances, you need to override the equals () and hashcode () methods in the Person class.

import java.util.*;

public class s6_3 {
    public static void main(String[] args) {
        ArrayList<Person> list = new ArrayList<>();
        list.add(new Person("Zhang San", 12));
        list.add(new Person("Li Si", 12));
        list.add(new Person("Wang Wu", 16));
        list.add(new Person("Li Si", 12));

        HashSet<Person> hs = new HashSet<>();

        Iterator it = list.iterator();
        while (it.hasNext()) hs.add((Person) it.next());

        System.out.println("Delete duplicate objects:");
        System.out.println(hs);
    }
}

public class Person {

    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person() {

    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }

    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person)) return false;
        Person p = (Person) o;
        return this.name.equals(p.name) && this.age == p.age;
    }

    public String toString() {
        return "{" + name + "," + age + "}";
    }
}

Operation screenshot:

4,

Write a program to obtain 10 random integers between 1 and the specified value (n). The requirements are as follows:

• (1) it is required that random numbers cannot be repeated. The n value is entered by the keyboard.

import java.util.*;

public class SixDemo {
    public static void main(String[] args) {
        //1. Get 10 numbers of [1,n]

        //Instantiate an object that can generate random numbers
        Random r = new Random();
        //Enter n
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        //Define a container for storing numbers
        ArrayList<Integer> list = new ArrayList<>();
        //If the randomly generated number [1,n] is not included in the list set, it will be stored
        for (int i = 0; i < 10; i ++ ) {
            int m = r.nextInt(n) + 1;//This step must be listed separately, and the function cannot be brought in directly, otherwise random numbers will be generated many times
            while (!(list.contains(m))) list.add(m);
        }


        for (Integer li : list) {
            System.out.println(li);
        }

    }
}

Operation screenshot:

When there are almost no repeats in the range of 1000 ~ 1 in figure.

When the range is 1 ~ 5, there will be several repeated elements. At this time, there are only 5 random numbers that do not repeat.

• (2) add three Person objects to the HashSet set, treat the Person with the same name as the same Person, and do not add them repeatedly.

Tip: define the name and age attributes in the Person class, override the hashCode() method and the equals() method, and compare the name attribute of the Person class. If the name is the same, the return value of the hashCode() method is the same, and the equals method returns true.

import java.util.*;

public class SixDemo {
    public static void main(String[] args) {

        HashSet<Person> hs = new HashSet<>();
        hs.add(new Person("Zhang San", 12));
        hs.add(new Person("Li Si", 12));
        hs.add(new Person("Zhang San", 14));

        System.out.println(hs);
    }
}

public class Person {
    private String name;
    private int age;

    public void setName(String name) {
        this.name = name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public Person() {

    }

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public int hashCode() {
        return name.hashCode();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Person)) return false;
        Person p = (Person) o;
        return this.name.equals(p.name);
    }

    public String toString() {
        return "{" + name + "," + age + "}";
    }

}

Operation screenshot:

 

5,

Write a program to store the names and grades of a group of student objects into a TreeSet, and complete the following requirements:

• (1) automatically arrange in descending order according to the scores, and output the sorting results.

import java.util.*;

public class SixDemo {
    public static void main(String[] args) {
        TreeSet<Student> ts = new TreeSet<>(new Comparator<>() {//To generate Student parameters directly in compare, you need to add Student generics here
            @Override
            public int compare(Object o1, Object o2) {
                Student stu1 = (Student) o1;
                Student stu2 = (Student) o2;
                //Note that the score s of some Student objects here are equal. If they are equal, they are listed in the order of addition

                //if (stu2.getScore() >= stu1.getScore()) return 1;
                //else return -1;

                int i = stu2.getScore() - stu1.getScore();
                return i == 0 ? stu1.getName().compareTo(stu2.getName()) : i;//Reverse order
            }
        });

        ts.add(new Student("Zhang San", 67));
        ts.add(new Student("Li Si", 98));
        ts.add(new Student("Wang Wu", 87));
        ts.add(new Student("Zhao Liu", 67));

        System.out.println(ts);
    }
}



public class Student {
    private String name;
    private int score;

    public Student(String name, int score) {
        this.name = name;
        this.score = score;
    }

    public Student() {

    }

    public void setName(String name) {
        this.name = name;
    }

    public void setScore(int score) {
        this.score = score;
    }

    public String getName() {
        return name;
    }

    public int getScore() {
        return score;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", score=" + score +
                '}';
    }

}

  

• (2) remove duplicate elements from an unordered array and sort them in ascending order.

import java.util.*;

public class SixDemo2 {
    public static void main(String[] args) {

        ArrayList<Integer> list = new ArrayList<>();
        list.add(3);
        list.add(23);
        list.add(12);
        list.add(99);
        list.add(23);
        System.out.println("Original unordered array" + list);

        HashSet<Integer> hs = new HashSet<>();

        Iterator it2 = list.iterator();
        while (it2.hasNext()) {
            Integer i2 = (Integer) it2.next();
            hs.add(i2);
        }

        System.out.println("De duplication but still out of order" + hs);

        //Ascending order
        //There is no need to use Comparator here, because the wrapper class of the basic type has implemented the Comparable interface of the first method
        TreeSet<Integer> ts = new TreeSet<>(new Comparator<Integer>() {
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1 - o2;
            }
        });

        Iterator it = hs.iterator();
        while (it.hasNext()) {
            Integer i = (Integer) it.next();
            ts.add(i);
        }

        System.out.println("Ascending order:" + ts);

    }
}

6,

Write a program to read an indefinite number of integers, and then find the number with the highest frequency. When the input is 0, the input is ended. For example:

If the input data is 2 # 3 # 40 # 3 # 54 - 3 # 3 # 2 # 0, the occurrence frequency of number 3 is the highest. Please enter one number at a time.

If the number with the highest frequency is not one but multiple, all of them should be output. For example, in the linear table 9 # 30 # 3 # 9 # 3 # 2 # 4, both 3 and 9 appear twice, and both 3 and 9 should be output.

Tip: you can define two sets, one to store all the input data and the other to store the most frequent numbers.

import java.util.*;

public class SixDemo {
    public static void main(String[] args) {

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

        //Use the list1 set to store all the numbers entered
        System.out.println("Please enter any number of numbers (0 as stop sign):");
        for (int i = 0; ; i ++ ) {
            Scanner sc = new Scanner(System.in);
            int n = sc.nextInt();
            if (n != 0) list1.add(n);
            else break;
        }

        //Find the largest number in list1 to assign value to count array
        int max = 0;
        for (int i = 1; i < list1.size(); i ++ ) {
            if (list1.get(i) >= list1.get(i - 1)) max = list1.get(i);
            else max = list1.get(i - 1);
        }

        //Store the number with the highest frequency into list2
        List<Integer> list2 = new LinkedList<>();
        int[] count = new int[max + 1];

        for (Integer i : list1) {
            count[i] = 0;
            for (Integer j : list1) {
                if (i == j) count[i] ++ ;
            }

            //If there is no element, add the element directly. If there is an element, judge the size
            //If the new element is large, delete all the old elements; If equal, add new elements directly; Otherwise, the next round
            if (list2.size() >= 1) {
                if (count[i] > count[list2.get(0)]) {
                    //list2.removeAll(list2);
                    //The following is wrong, List2 The value of size () will always change
                    // for (int n = 0; n < list2.size(); n ++ ) list2.remove(n);
                    int size = list2.size();
                    for (int n = 0; n < size; n ++ ) list2.remove(0);//The first element is always deleted here, not the nth, because the position of the nth number will change
                    list2.add(i);
                }
                else if (count[i] == count[list2.get(list2.size() - 1)]) {
                    list2.add(i);
                }
                else continue;
            }
            else list2.add(i);
            System.out.println("list2 present situation:" + list2);
        }

        System.out.println("Before weight removal:" + list2);

        //list2 set de duplication
        HashSet<Integer> hs = new HashSet<>();
        for (Integer i : list2) {
            hs.add(i);
        }

        //The number with the highest output frequency
        System.out.println("The number with the highest frequency after de duplication is:" + hs);

    }
}

7,

Select the appropriate Map set, save the user names and passwords of five users, and then print these key value pairs.  

import java.util.Comparator;
import java.util.Map;
import java.util.TreeMap;

public class SixDemo {
    public static void main(String[] args) {

        Map<String, String> map = new TreeMap<>(new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return 1;//In the order of addition
            }
        });

        map.put("Zhang San","202021");
        map.put("Li Si","23426");
        map.put("Wang Wu","23045");
        map.put("Zhao Liu", "sjhgo");
        map.put("sgfhfow", "shgiowh");

        System.out.println("Five pairs of user names and passwords are:" + map);

    }
}

8,

Count the number of occurrences of each word in the string, using HashMap. For example: "Today, We have a class of java, as we kown, java is an object oriented programming language, and java is fun! wish you enjoy it!", The statistical results are stored in the following form:

a-->1

an-->1

and-->1

as-->1......

is-->2

Tip: use string The split ("[\ n \ t \ R.,;:!? ()]) method performs word segmentation, spaces, punctuation, etc.

Idea:

String. The split () method can divide a long sentence into several words (that is, it can be stored in a string array)

import java.util.*;

public class SixDemo {
    public static void main(String[] args) {

        Map<String, Integer> hm = new HashMap<>();
        String strs = "Today, We have a class of java, as we kown, java is an object oriented  programming language, and java is fun! wish you enjoy it!";
        String[] str = strs.split("[ \n\t\r.,;:!?()]");

        for (int i = 0; i < str.length; i ++ )
            if (!hm.containsKey(str[i])) hm.put(str[i], 1);
            else
            {
                Integer n = hm.get(str[i]);
                hm.put(str[i], n + 1);
            }

        System.out.println("The statistical results are as follows:");

        Iterator<String> it = hm.keySet().iterator();
        while (it.hasNext()) {
            String keyName = it.next();
            System.out.println(keyName + "->" + hm.get(keyName));
        }

    }
}

Operation screenshot:

 

Topics: Java Back-end