首页 > 解决方案 > 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**>

标签: javasortingcollections

解决方案


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}]

推荐阅读