如何在Java中通过ID过滤重复的ArrayList-Spring Boot Data JPA

时间:2018-09-25 16:47:20

标签: java spring spring-boot arraylist spring-data-jpa

在我的测试应用程序中,我试图创建一个springboot api。我创建了一个api,通过它我可以获取包含重复id(sid)的对象列表。现在,我想按sid过滤该列表,然后将值(custRefId)与相应的id合并。

Api的列表输出:

[
    {
        "sId": 101,
        "sName": "Nike",
        "custRefId": "S1234567890a1001INR"
    },
    {
        "sId": 201,
        "sName": "Addidas",
        "custRefId": "S1234567895a1004INR"
    },
    {
        "sId": 501,
        "sName": "U.S Polo",
        "custRefId": "S1234567000a1258INR"
    },
    {
        "sId": 501,
        "sName": "U.S Polo",
        "custRefId": "S1234567000a1011INR"
    },
    {
        "sId": 501,
        "sName": "U.S Polo",
        "custRefId": "S1234567899a1008INR"
    }
]

必需的输出:

{
        "sId": 101,
        "sName": "Nike",
        "custRefId": "S1234567890a1001INR"
    },
    {
        "sId": 201,
        "sName": "Addidas",
        "custRefId": "S1234567895a1004INR"
    },
    {
        "sId": 501,
        "sName": "U.S Polo",
        "custRefId": {"S1234567000a1258INR","S1234567000a1011INR","S1234567899a1008INR"}
    }

enter code here

我的测试豆

package com.example.easynotes.model;

import java.io.Serializable;
import java.util.Date;

import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import com.example.easynotes.controller.CompositeKeyEntity;

@Entity(name = "TestApi")
@Table(name="test")
public class TestApi implements Serializable{

    /**
     * 
     */
    private static final long serialVersionUID = -6972984895555407355L;

    @EmbeddedId
    private CompositeKeyEntity CompositeKeyEntity;

    @Column(name = "S_Id")
    private Long sId;

    @Column(name = "S_Name")
    private String sName;

    @Column(name = "B_Id")
    private int bId;

    @Column(name = "B_Name")
    private String bName;

    @Column(name = "Login_Date")
    private Date loginDate;

    @Column(name = "Amount")
    private int amount;

    @Column(name = "B_Acc")
    private String bAccount;

    public TestApi() {
        super();
    }

    public TestApi(com.example.easynotes.controller.CompositeKeyEntity compositeKeyEntity, Long sId, String sName,
            int bId, String bName, Date loginDate, int amount, String bAccount) {
        super();
        CompositeKeyEntity = compositeKeyEntity;
        this.sId = sId;
        this.sName = sName;
        this.bId = bId;
        this.bName = bName;
        this.loginDate = loginDate;
        this.amount = amount;
        this.bAccount = bAccount;
    }

    public CompositeKeyEntity getCompositeKeyEntity() {
        return CompositeKeyEntity;
    }

    public void setCompositeKeyEntity(CompositeKeyEntity compositeKeyEntity) {
        CompositeKeyEntity = compositeKeyEntity;
    }

    public Long getsId() {
        return sId;
    }

    public void setsId(Long sId) {
        this.sId = sId;
    }

    public String getsName() {
        return sName;
    }

    public void setsName(String sName) {
        this.sName = sName;
    }

    public int getbId() {
        return bId;
    }

    public void setbId(int bId) {
        this.bId = bId;
    }

    public String getbName() {
        return bName;
    }

    public void setbName(String bName) {
        this.bName = bName;
    }

    public Date getLoginDate() {
        return loginDate;
    }

    public void setLoginDate(Date loginDate) {
        this.loginDate = loginDate;
    }

    public int getAmount() {
        return amount;
    }

    public void setAmount(int amount) {
        this.amount = amount;
    }

    public String getbAccount() {
        return bAccount;
    }

    public void setbAccount(String bAccount) {
        this.bAccount = bAccount;
    }

}

测试Api存储库:

package com.example.easynotes.repository;
import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.example.easynotes.controller.CompositeKeyEntity;
import com.example.easynotes.model.TestApi;

@Repository
public interface TestRepo extends JpaRepository<TestApi, CompositeKeyEntity>{

    @Query(
            value = "SELECT * FROM test WHERE S_Id = :sId",
            nativeQuery = true
    )
    public TestApi getSDataById(@Param("sId")long sId);

    @Query(value="SELECT h.S_Id,h.S_Name,h.B_Id,h.B_Name,h.Login_Date,h.Amount,h.B_Acc,h.S_Acc,h.B_Ref_Id,h.CRR  FROM test h order by h.Login_Date asc",nativeQuery = true )
    public List<TestApi> getSellerData();


    @Query(
            value = "SELECT * FROM test WHERE S_Id = :sId and S_Name =:sName",
            nativeQuery = true
    )
    public List<TestApi> findDataBySIDAndSName(long sId, String sName);

}

TestController类:

package com.example.easynotes.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Stream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.easynotes.model.TestApi;
import com.example.easynotes.model.TestBean;
import com.example.easynotes.repository.TestRepo;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;

@RestController
@RequestMapping("/LCRF")
public class TestController {


    List<TestApi> lcrf = new ArrayList<TestApi>();
    List<TestApi> tmp = new ArrayList<TestApi>();

    @Autowired
    TestRepo lRepo;
    @Autowired
    Assembler assembler;

    @GetMapping("/allData")
    public List<TestBean> getAll()
    {
        getMergeIds(assembler.sBBeanList(lRepo.getSellerData()));

        return assembler.sBBeanList(lRepo.getSellerData());
    }

    @GetMapping("/allData/{sellerId}")
    public TestApi getSellerDetail(@PathVariable(value = "sellerId")Long sellerId)
    {

        return lRepo.getSDataById(sellerId);
    }

    @GetMapping("/allData/{sId}/{sName}")
    public List<TestApi> getDataByIdAndName(@PathVariable(value = "sId")Long sId,@PathVariable(value = "sId")String sName)
    {

        lcrf = lRepo.findDataBySIDAndSName(sId, sName);
        return lcrf;    
    }

    public List<TestMergeIds> getMergeIds(List<TestBean> testBean)
    {
        List<TestBean> testList = new ArrayList<TestBean>();
        Multimap<Long, String> multiMap = ArrayListMultimap.create();
        TestMergeIds testMergeIdsBean = new TestMergeIds(); 
        for(TestBean bean: testBean) {

            multiMap.put(bean.getsId(), bean.getCustRefId());

        }
        Set<Long> keys = multiMap.keySet();
        List<String> targetList = new ArrayList<>();
        for (Long key : keys) {

        }
        System.out.println("Print list values ---111---"+targetList);
        return null;


    }
}

CompositeKeyEntity类:

package com.example.easynotes.controller;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Embeddable;

@Embeddable
public class CompositeKeyEntity implements Serializable{

    private static final long serialVersionUID = 1581433221916043048L;

    @Column(name="S_Acc")
    private String sAccount;

    @Column(name="B_Ref_Id")
    private String bRefId;

    @Column(name="CRR")
    private String crr;

    public String getsAccount() {
        return sAccount;
    }

    public void setsAccount(String sAccount) {
        this.sAccount = sAccount;
    }

    public String getbRefId() {
        return bRefId;
    }

    public void setbRefId(String bRefId) {
        this.bRefId = bRefId;
    }

    public String getCrr() {
        return crr;
    }

    public void setCrr(String crr) {
        this.crr = crr;
    }





}

汇编程序类:

package com.example.easynotes.controller;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;

import com.example.easynotes.model.TestApi;
import com.example.easynotes.model.TestBean;

@Component
public class Assembler {

    public List<TestBean> sBBeanList(final List<TestApi> testApiList)
    {
        final List<TestBean> SellerBuyerBeanList = new ArrayList<>(testApiList.size());
        if(!testApiList.isEmpty())
        {
            for(final TestApi lcrfApiEntity : testApiList) {

                final TestBean sellerBuyerBeanlist = new TestBean();
                BeanUtils.copyProperties(lcrfApiEntity, sellerBuyerBeanlist);
                sellerBuyerBeanlist.setCustRefId(formSellerBuyerRefId(lcrfApiEntity.getCompositeKeyEntity()));
                SellerBuyerBeanList.add(sellerBuyerBeanlist);
            }

        }


        return SellerBuyerBeanList;

    }

    private String formSellerBuyerRefId(final CompositeKeyEntity compositeKeyEntity)
    {
        StringBuilder sBuilder=new StringBuilder();
        sBuilder.append(compositeKeyEntity.getsAccount());
        sBuilder.append(compositeKeyEntity.getbRefId());
        sBuilder.append(compositeKeyEntity.getCrr());
        return sBuilder.toString();

    }
}
enter code here

2 个答案:

答案 0 :(得分:2)

---------------------------- 方法1,使用java.util.Set ----------------------------

一种简单的方法是使用java.util.Set而不是java.util.List,请尝试以下操作:

首先通过添加“等于”和“ hashCode”方法来修改您的实体( TestApi.java ):

@GetMapping("/allData/{sId}/{sName}")
public Set<TestApi> getDataByIdAndName(@PathVariable(value = "sId")Long sId,@PathVariable(value = "sId")String sName)
{
    lcrf = lRepo.findDataBySIDAndSName(sId, sName);
    return new java.util.LinkedHashSet(lcrf);    
}

这样,java.util.Set将能够在整个列表中变得与众不同,然后修改您的 TestController.java ,使其返回Set而不是List,如下所示:

@Query(
        value = "SELECT DISTINCT sId, sName, custRefId FROM test WHERE S_Id = :sId and S_Name =:sName",
        nativeQuery = true
)
public List<UniqueTestApi> findDataBySIDAndSName(long sId, String sName);

对于要包装为唯一元素列表的每个@Entity,您都必须执行相同的操作。

---------------------------- 方法2,指定查询 ----------------------------

首先,您必须创建一个指定接口来表示结果,然后将TestRepo.java修改为:

public static interface UniqueTestApi {
    Long getSId();
    String getSName();
    String getCustRefId();
}

此外,UniqueTestApi接口应如下所示:

@GetMapping("/allData/{sId}/{sName}")
public List<UniqueTestApi> getDataByIdAndName(@PathVariable(value = "sId")Long sId,@PathVariable(value = "sId")String sName)
{

    lcrf = lRepo.findDataBySIDAndSName(sId, sName);
    return lcrf;    
}

此后,您必须在 TestController.java 上将方法修改为:

.Cells

答案 1 :(得分:1)

您可以使用Java 8 Streams将其过滤为一组:

Set<TestApi> filteredSet = testApiList.stream()
.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TestApi::getSId))));

如果要保留它作为列表的另一种Java 8功能:

//Temporary set of Long that will filter the Ids
    Set<Long> tempSet = new HashSet<>();

    //Duplicated Ids
    List<Long> duplicatedList = new ArrayList<>();

    //The same list but filtered
    testApiList.removeIf(e -> {
        boolean duplicated = !tempSet.add(e.getSId());
        if (duplicated) duplicatedList.add(e.getSId());
        return duplicated;
    });

编辑

添加了重复的列表。