java - Need to sort array object based on other string array and remove unmatch object
问题描述
Need to sort array object based on other string array and remove unmatch object
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Test {
String name;
int no;
public String getName() {
return name;
}
public int getNo() {
return no;
}
public void setName(String name) {
this.name = name;
}
public void setNo(int no) {
this.no = no;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", no=" + no +
'}';
}
public static Test createStudent(String name, int no) {
Test student = new Test();
student.setName(name);
student.setNo(no);
return student;
}
public static void sortStudentInArrayList(List<String> scppriority) {
List<Test> students = new ArrayList<>();
Test student1 = createStudent("SCP1", 3);
students.add(student1);
Test student2 = createStudent("SCP2", 1);
students.add(student2);
Test student3 = createStudent("SCP3", 5);
students.add(student3);
Test student4 = createStudent("SCP4", 2);
students.add(student4);
//students.retainAll(scppriority);
System.out.println("Original students list: " + students);
Collections.sort(students, Comparator.comparing(s -> scppriority.indexOf(s.getName())));
}
public static void main(String[] args) {
List<String> string2 = new ArrayList<String>();
string2.add("SCP2");
string2.add("SCP3");
sortStudentInArrayList(string2);
}
}
<** output Original students list: [Student{name='SCP1', no=3}, Student{name='SCP4', no=2}, Student{name='SCP2', no=1}, Student{name='SCP3', no=5}] need to remove unmatch from student list, Thanks in Advance**>
解决方案
Try this,
List<Test> result = students.stream()
.filter(student -> scppriority.contains(student.getName()))
.sorted(Comparator.comparing(s -> scppriority.indexOf(s.getName())))
.collect(Collectors.toList());
System.out.println("Original students list: " + result);
Output:
Original students list: [Student{name='SCP2', no=1}, Student{name='SCP3', no=5}]
推荐阅读
- java - Java REGEX - 从列表中添加可能性
- windows - 是否可以将 PowerShell 窗口注入 Windows 任务栏?
- sql-server - 使用 OPENJSON 触发向插入的记录添加值
- azure-active-directory - 为资源“组”的属性“可见性”指定了不受支持或无效的查询过滤器子句
- hyperledger - 如何安装超级账本资源管理器并将其集成到 iroha?
- python - 如何在 PySpark 中编码 DateTime 值?
- excel - VBA在最后一列之后创建两列,带有数据的特定行
- python - 我可以安全地忽略这些错误吗?
- angular - 使用路由参数的角度路由路径匹配
- c# - 泛型。调用一个方法两次,但每次参数都是不同的类型