当前位置:网站首页>Uniqueness and ordering in set
Uniqueness and ordering in set
2022-07-24 21:28:00 【Wang Xiaoya】
1. Remove duplicate values
stay List Remove duplicate numeric values from the set , The requirements are as simple as possible ( With the help of other sets !!)
package com.B.Container_13.Set.MAp.Practice;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
// stay List Remove duplicate numeric values from the set , The requirements are as simple as possible ( With the help of other sets !!)
public class A5 {
public static void main(String[] args) {
// establish list A collection of objects
ArrayList<Integer> list = new ArrayList<Integer>();
// Additive elements
list.add(12);
list.add(15);
list.add(24);
list.add(12);
list.add(24);
// establish set aggregate
HashSet<Integer> set = new HashSet<Integer>();
// Create a new list aggregate
List newList = new ArrayList();
// take list The elements of the collection are added to set aggregate , Achieve the purpose of removing duplicate numerical values
for (Integer s :list) {
if(set.add(s)){
newList.add(s);
}
}
System.out.println( " The collection after de duplication : " + newList);
}
}
Output :
The collection after de duplication : [12, 15, 24]
Process ended , Exit code 02. Remove duplicate values
There are several books and information ( Include name title、 author author、 pricing price) Need to store to set Collection , Ensure that there are no duplicate elements in the collection , And traverse to see . It can be considered that all books with the same information are duplicate data .
package com.B.Container_13.Set.MAp.Practice;
// Books and information ( Include name title、 author author、 pricing price)
public class A7_books {
private String title;
private String author;
private double price;
public A7_books() {
}
public A7_books(String title, String author, double price) {
this.title = title;
this.author = author;
this.price = price;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
// Rewriting methods
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
A7_books a7_01 = (A7_books) o;
if (Double.compare(a7_01.price, price) != 0) return false;
if (title != null ? !title.equals(a7_01.title) : a7_01.title != null) return false;
return author != null ? author.equals(a7_01.author) : a7_01.author == null;
}
@Override
public int hashCode() {
int result;
long temp;
result = title != null ? title.hashCode() : 0;
result = 31 * result + (author != null ? author.hashCode() : 0);
temp = Double.doubleToLongBits(price);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
}
Test class :
package com.B.Container_13.Set.MAp.Practice;
import java.util.HashSet;
// There are several books and information ( Include name title、 author author、 pricing price)
// Need to store to set Collection , Ensure that there are no duplicate elements in the collection , And traverse to see . It can be considered that all books with the same information are duplicate data .
public class A7 {
public static void main(String[] args) {
// Create objects
HashSet<A7_books> hs = new HashSet<A7_books>();
// Additive elements
A7_books book1 = new A7_books(" Journey to the west "," Wu chengen ",69.9);
A7_books book2 = new A7_books(" The romance of The Three Kingdoms "," Luo Guanzhong ",59.9);
A7_books book3 = new A7_books(" Journey to the west "," Wu chengen ",69.9);
A7_books book4 = new A7_books(" A dream of red mansions "," Cao xueqin ",58.9);
A7_books book5 = new A7_books(" Water margin "," Shi Naian ",46.9);
hs.add(book1);
hs.add(book2);
hs.add(book3);
hs.add(book4);
hs.add(book5);
// Output
for (A7_books h : hs) {
System.out.println("《"+h.getTitle()+"》 The author is "+h.getAuthor()+", The price for "+h.getPrice()+" element ");
}
Tom
}
}
Output results :
《 Water margin 》 The author is Shi Naian , The price for 46.9 element
《 A dream of red mansions 》 The author is Cao Xueqin , The price for 58.9 element
《 Journey to the west 》 The author is Wu Chengen , The price for 69.9 element
《 The romance of The Three Kingdoms 》 The author is Luo Guanzhong , The price for 59.9 element
Process ended , Exit code 03. Sort ( There are priorities )
In an exam , The student's grade information is as follows ( Public attribute ): full name (String) Age (int) achievement (int): Tom 20 90; Jerry 22 95; John 20 100; Lily 22 100 ;Lucy 22 90; Kevin 22 90 Please use... Separately Comparable and Comparator The two interfaces sort the grades of the above students in descending order , If the results are the same , Based on the ranking of grades, they are ranked according to their age , Grades and age are the same , Then sort according to the dictionary order of names .
What happened :
The output results are not in descending order
Reasons for appearance :
Wrong sorting logic

Improvement measures :
In exchange for s1 and s2 Location

Complete code :
Comparable Interface sorting :
package com.B.Container_13.Set.MAp.Practice;
//Comparable Interface sorting
// Students
// In an exam , The student's grade information is as follows ( Public attribute ): full name (String) Age (int) achievement (int)
//Tom 20 90; Jerry 22 95; John 20 100; Lily 22 100 ;Lucy 22 90; Kevin 22 90
public class A8_Student01 implements Comparable<A8_Student01> {
private String name;
private int age;
private int score;
public A8_Student01() {
}
public A8_Student01(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public int compareTo(A8_Student01 s) {
// Grades are sorted in descending order , From big to small
int num = s.score - this.score;
// At the same age , Sort by age
int num1 = num == 0 ? this.age - s.age : num;
// Grades and age are the same , Then sort according to the dictionary order of names .
int num2 = num1 == 0 ? this.name.compareTo(s.name) : num1;
return num2;
}
}
Test class :
package com.B.Container_13.Set.MAp.Practice;
//Comparable Interface sorting
// Please use... Separately Comparable and Comparator The two interfaces sort the grades of the above students in descending order ,
// If the results are the same , Based on the ranking of grades, they are ranked according to their age ,
// Grades and age are the same , Then sort according to the dictionary order of names .
import java.util.TreeSet;
public class A8_01 {
public static void main(String[] args) {
// Create a collection object
TreeSet<A8_Student01> stu = new TreeSet<A8_Student01>();
// Create student objects
A8_Student01 s1 = new A8_Student01("Tom", 20,90);
A8_Student01 s2 = new A8_Student01("Jerry", 22,95);
A8_Student01 s3 = new A8_Student01("John", 20,100);
A8_Student01 s4 = new A8_Student01("Lily", 22,100);
A8_Student01 s5 = new A8_Student01("Lucy", 22,90);
A8_Student01 s6 = new A8_Student01("Kevin", 22,90);
// Add students to the collection
stu.add(s1);
stu.add(s2);
stu.add(s3);
stu.add(s4);
stu.add(s5);
stu.add(s6);
// Ergodic set
for (A8_Student01 s : stu) {
System.out.println(s.getName() +","+s.getAge()+","+s.getScore());
}
}
}
Running results :
John,20,100
Lily,22,100
Jerry,22,95
Tom,20,90
Kevin,22,90
Lucy,22,90
Process ended , Exit code 0
Comparator Interface sorting :
package com.B.Container_13.Set.MAp.Practice;
Comparator Interface sorting
// In an exam , The student's grade information is as follows ( Public attribute ): full name (String) Age (int) achievement (int):
public class A8_Student02 {
String name;
int age;
int score;
public A8_Student02() {
}
public A8_Student02(String name, int age, int score) {
this.name = name;
this.age = age;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
@Override
public String toString() {
return "A8_Student02{" +
"name='" + name + '\'' +
", age=" + age +
", score=" + score +
'}';
}
}
Test class :
package com.B.Container_13.Set.MAp.Practice;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
//Comparator Interface sorting
public class A8_02 {
public static void main(String[] args) {
// Create a TreeSet A collection of objects
Set<A8_Student02> treeSet =new TreeSet<A8_Student02>(new Comparator<A8_Student02>() {
@Override
public int compare(A8_Student02 s1, A8_Student02 s2) {
// Grades are sorted in descending order , From big to small
int num = s2.getScore() - s1.getScore();
// At the same age , Sort by age
int num1 = num == 0 ? s1.getAge() - s2.getAge() : num;
// Grades and age are the same , Then sort according to the dictionary order of names .
int num2 = num1 == 0 ? s1.getName().compareTo(s2.getName()) : num1;
return num2;
}
});
// Create student objects
treeSet.add(new A8_Student02("Tom", 20,90));
treeSet.add(new A8_Student02("Jerry", 22,95));
treeSet.add(new A8_Student02("John", 20,100));
treeSet.add(new A8_Student02("Lily", 22,100));
treeSet.add(new A8_Student02("Lucy", 22,90));
treeSet.add(new A8_Student02("Kevin", 22,90));
// Traversal array
for (A8_Student02 s02 : treeSet) {
System.out.println(s02);
}
}
}
result :
A8_Student02{name='John', age=20, score=100}
A8_Student02{name='Lily', age=22, score=100}
A8_Student02{name='Jerry', age=22, score=95}
A8_Student02{name='Tom', age=20, score=90}
A8_Student02{name='Kevin', age=22, score=90}
A8_Student02{name='Lucy', age=22, score=90}
Process ended , Exit code 0
边栏推荐
- Kubernetes resource list: how to create resources?
- Mysql database commands
- Overview and installation of scientific computing toolkit scipyscipy
- [basic data mining technology] KNN simple clustering
- 93. Recursive implementation of combinatorial enumeration
- Baidu PaddlePaddle easydl helps improve the inspection efficiency of high-altitude photovoltaic power stations by 98%
- 731. My schedule II (segment tree or scoring array)
- Leetcode skimming -- bit by bit record 018
- 支付宝上股票开户安全吗
- [summary of Feature Engineering] explain what features are and the steps of feature engineering
猜你喜欢

Lecun proposed that mask strategy can also be applied to twin networks based on vit for self supervised learning!

Es+redis+mysql, the high availability architecture design is awesome! (supreme Collection Edition)

Multiplication and addition of univariate polynomials
![[blind box app mall system] function introduction after online unpacking](/img/c9/3d13409113a3671555c4744eeb3913.jpg)
[blind box app mall system] function introduction after online unpacking

Eight transformation qualities that it leaders should possess
![[summary of Feature Engineering] explain what features are and the steps of feature engineering](/img/29/f9643affd3aaf9d83c5b81394d29a7.png)
[summary of Feature Engineering] explain what features are and the steps of feature engineering
Hilditch refinement (implementation I)

CAD sets hyperlinks to entities (WEB version)

Sword finger offer 15. number of 1 in binary

Summary of yarn capacity scheduler
随机推荐
[Development Tutorial 4] open source Bluetooth heart rate waterproof sports Bracelet - external flash reading and writing
class file has wrong version 55.0, should be 52.0
[feature construction] construction method of features
Eight transformation qualities that it leaders should possess
[advanced data mining technology] Introduction to advanced data mining technology
Oracle creates table spaces and views table spaces and usage
[shallow copy and deep copy], [heap and stack], [basic type and reference type]
High soft course summary
How to choose securities companies that support flush? Is it safe to open an account on your mobile phone
95. Puzzling switch
Spark related FAQ summary
Unfair distribution
Summary of yarn capacity scheduler
findContours
Using skills and design scheme of redis cache (classic collection version)
01_ UE4 advanced_ PBR material
Pressing Ctrl will cause several key press messages
Brand new: the latest ranking of programming languages in July
Multiplication and addition of univariate polynomials
Lazily doing nucleic acid and making (forging health code) web pages: detained for 5 days