java接口返回參數按照請求參數進行排序方式

java接口返回參數按照請求參數進行排序

在項目實際開發中可能遇到過這種問題,接口請求參數順序是[a,b,c],結果返回的數據是[bObject,cObject,aObject],導致這種原因可能是底層采用瞭設計模式,或者是表拼接查詢,本文主要就是為瞭實現這種功能,采用流的方法

代碼實現

import lombok.Data;
import java.io.Serializable;
/**
 * @description 模擬接口結果類
 * @author: WilsonMeng
 * @create: 2021-01-26 14:26
 **/
@Data
public class SkuInfo implements Serializable {
    private static final long serialVersionUID = -6242151519713186291L;
    /**
     * spuId
     */
    private String spuId;
    /**
     * skuId
     */
    private String skuId;
    /**
     * 商品名稱
     */
    private String productName;
    /**
     * 商品圖片
     */
    private String picture;
    /**
     * 商品鏈接
     */
    private String link;
}

排序

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.wanli.databoard.dto.SkuInfo;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
 * @description
 * @author: WilsonMeng
 * @create: 2021-01-26 14:28
 **/
public class SkuSortTest {
    public static void main(String[] args) {
        List<String> skuIdList = Arrays.asList("sku1", "sku2", "sku3", "sku4");
        //用於模擬接口入參
        System.out.println("skuid列表:" + JSON.toJSONString(skuIdList));
        System.out.println();
        List<SkuInfo> skuInfoList = Lists.newArrayList();
        SkuInfo s1 = new SkuInfo();
        s1.setSpuId("spu1");
        s1.setSkuId("sku1");
        s1.setProductName("商品1");
        s1.setPicture("p1");
        s1.setLink("link1");
        skuInfoList.add(s1);
        SkuInfo s4 = new SkuInfo();
        s4.setSpuId("spu1");
        s4.setSkuId("sku4");
        s4.setProductName("商品2");
        s4.setPicture("p4");
        s4.setLink("link4");
        skuInfoList.add(s4);
        SkuInfo s3 = new SkuInfo();
        s3.setSpuId("spu2");
        s3.setSkuId("sku3");
        s3.setProductName("商品3");
        s3.setPicture("p3");
        s3.setLink("link3");
        skuInfoList.add(s3);
        SkuInfo s2 = new SkuInfo();
        s2.setSpuId("spu2");
        s2.setSkuId("sku2");
        s2.setProductName("商品2");
        s2.setPicture("p2");
        s2.setLink("link2");
        skuInfoList.add(s2);
        //用於模擬接口入參
        System.out.println("skuInfoList列表:" + JSON.toJSONString(skuInfoList));
        System.out.println();
        //按照請求參數進行排序
        List<SkuInfo> resultList = skuInfoList.stream().sorted(getSkuIdListComparator(skuIdList)).collect(Collectors.toList());
        System.out.println("排序完成後的結果:" + JSON.toJSONString(resultList));
    }
    private static Comparator<SkuInfo> getSkuIdListComparator(List<String> skuIds) {
        return (o1, o2) -> {
            int order1 = 0, order2 = 0;
            for (int i = 0; i < skuIds.size(); i++) {
                if (Objects.equals(o1.getSkuId(), skuIds.get(i))) {
                    order1 = i;
                }
                if (Objects.equals(o2.getSkuId(), skuIds.get(i))) {
                    order2 = i;
                }
            }
            return order1 - order2;
        };
    }
}

代碼運行結果:

skuid列表:[“sku1″,”sku2″,”sku3″,”sku4”]

skuInfoList列表:[{“link”:”link1″,”picture”:”p1″,”productName”:”商品1″,”skuId”:”sku1″,”spuId”:”spu1″},{“link”:”link4″,”picture”:”p4″,”productName”:”商品2″,”skuId”:”sku4″,”spuId”:”spu1″},{“link”:”link3″,”picture”:”p3″,”productName”:”商品3″,”skuId”:”sku3″,”spuId”:”spu2″},{“link”:”link2″,”picture”:”p2″,”productName”:”商品2″,”skuId”:”sku2″,”spuId”:”spu2″}]

排序完成後的結果:[{“link”:”link1″,”picture”:”p1″,”productName”:”商品1″,”skuId”:”sku1″,”spuId”:”spu1″},{“link”:”link2″,”picture”:”p2″,”productName”:”商品2″,”skuId”:”sku2″,”spuId”:”spu2″},{“link”:”link3″,”picture”:”p3″,”productName”:”商品3″,”skuId”:”sku3″,”spuId”:”spu2″},{“link”:”link4″,”picture”:”p4″,”productName”:”商品2″,”skuId”:”sku4″,”spuId”:”spu1″}]

java通過接口進行排序

描述

對學生排序,先按成績由大到小排序,成績相同按姓名字母排序,姓名相同再按學號由小到大排序。

  package src7;
    import java.util.*;
    class Student implements Comparable<Student>  {
        private String name;
        private int id;
        private int grade;
    public Student(String name, int id, int grade) {
        this.name = name;
        this.id = id;
        this.grade = grade;
    }
    public int compareTo(Student o) {
            Student s = (Student) o;
            if (this.grade>s.grade) {
                return -1;//返回負數,當前成績排前
            } else if (this.grade == s.grade) {
//                if (this.name.hashCode() < s.name.hashCode()) {
//                    return -1;          //使用hashCode()
                if (this.name.compareTo(s.name)<0) {
                    return -1;            //使用compareTo
//                } else if (this.name.hashCode() == s.name.hashCode()) {
                } else if (this.name.compareTo(s.name)==0) {
                    if (this.id < s.id) {
                        return -1;
                    } else if (this.id == s.id) {
                        return 0;//此處說明姓名學號成績全部相同
                    } else {
                        return 1;
                    }
                } else {
                    return 1;// 返回正數,當前對象排後
                }
            } else {
                return 1;
            }
        }
    @Override
    public String toString() {
        return "姓名:" + this.name +",學號:"+this.id+ ",成績:" + this.grade + "\n";
    }
}
public class Test {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Student[] arr = new Student[3];
        for (int i = 0; i < arr.length; i++) {
            System.out.println("輸入第" + (i + 1) + "個學生的姓名、學號和成績:");
            String name = in.next();
            int id = in.nextInt();
            int grade = in.nextInt();
            arr[i] = new Student(name, id, grade);
        }
        System.out.println("排序前:");
        for(int i = 0; i < arr.length; i++){
            System.out.println(arr[i]);
        }
        System.out.println("排序後:");{
        List<Student>students=Arrays.asList(arr);
        Collections.sort(students);
        System.out.println(students);
        //也可以使用冒泡排序
        for(int i=0;i<arr.length;i++) {
            System.out.println(arr[i]);
        }
        }   
        }
    }

知識點

1.Comparable接口

包含的比較方法:

public interface Comparable< T >{
public int compareTo(T obj);
}

比較當前對象與外來對象,讓當前對象排前就返回負值,反之返回正值,相等返回0

關於Comparable接口的簡單舉例:對人的姓和名進行排序

package src7;
import java.util.*;
class Person implements Comparable<Person>{
    private final String lastname,firstname;//lastname表示姓 firstname表示名
    public Person(String lastname,String firstname){
        this.lastname=lastname;
        this.firstname=firstname;
    }
    public String lastname(){
        return lastname;
    }
    public String firstname(){
        return firstname;
    }
    public boolean equals(Object obj){
        Person n=(Person)obj;
        return (n.lastname.equals(lastname)&&n.firstname.equals(firstname));
    }
    public int hashCode(){
        return lastname.hashCode()+firstname.hashCode();
    }
    public String toString(){
        return lastname+" "+firstname;
    }
    public  int compareTo(Person n){
        if(lastname.compareTo(n.lastname)<0)
            return -1;
       if(lastname.compareTo(n.lastname)>0)
           return 1;
       else {
           if(firstname.compareTo(n.firstname)<0)
               return -1;
           if(firstname.compareTo(n.firstname)>0)
               return 1;
           else return 0;
       }
    }
}
public class Test {
    public static void main(String[]args){
        Person personArr[]={
                new Person("Zhang","Liang"),
                new Person("Li","Si"),
                new Person("Wang","Ning"),
                new Person("Zhang","San"),
                new Person("Chen","Yi")
        };
        List<Person>persons=Arrays.asList(personArr);
        Collections.sort(persons);
        System.out.println(persons);
    }
}

運行結果:

在這裡插入圖片描述

2.Comparator接口

包含的比較方法:

public interface Comparator< T >{
public int compare(T obj1,T obj2);
}

比較對象obj1和obj2,讓obj1位於obj2之前則返回負值

簡單舉例:對姓名排序

package src7;
import sun.awt.geom.AreaOp;
import java.util.*;
class Person{
    private String name;
    public Person(String name){
        this.name=name;
    }
    public String getName(){
        return name;
    }
    public String toString(){
        return name;
    }
}
 public class Test{
    static final Comparator<Person> ODER_BY_NAME=new Comparator<Person>() {
        @Override
        public int compare(Person o1, Person o2) {
            return o1.getName().compareTo(o2.getName());
        }
    };
     public static void main(String[] args) {
         Person personArr[]={
                new Person("ZhangLiang"),
                new Person("LiSi"),
                new Person("WangNing"),
                 new Person("ZhangSan"),
                new Person("ChenYi")
        };
         List<Person>persons=Arrays.asList(personArr);
        Collections.sort(persons,ODER_BY_NAME);
        System.out.println(persons);
         }
     }

運行結果:

在這裡插入圖片描述

以上為個人經驗,希望能給大傢一個參考,也希望大傢多多支持WalkonNet。

推薦閱讀: