首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Java - spring boot data jpa中根据id过滤重复的ArrayList

如何在Java - spring boot data jpa中根据id过滤重复的ArrayList
EN

Stack Overflow用户
提问于 2018-09-26 00:47:20
回答 2查看 2.3K关注 0票数 1

在我的测试应用程序中,我尝试创建一个springboot。我已经创建了一个api,通过它我可以获得一个包含重复id(sid)对象列表。现在,我希望通过sid过滤该列表,并将值(custRefId)与相应的ids合并。

Api的列表输出:

代码语言:javascript
复制
[
    {
        "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"
    }
]

所需的OutPut :

代码语言:javascript
复制
{
        "sId": 101,
        "sName": "Nike",
        "custRefId": "S1234567890a1001INR"
    },
    {
        "sId": 201,
        "sName": "Addidas",
        "custRefId": "S1234567895a1004INR"
    },
    {
        "sId": 501,
        "sName": "U.S Polo",
        "custRefId": {"S1234567000a1258INR","S1234567000a1011INR","S1234567899a1008INR"}
    }

代码语言:javascript
复制
enter code here

我的测试bean

代码语言:javascript
复制
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存储库:

代码语言:javascript
复制
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类:

代码语言:javascript
复制
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类:

代码语言:javascript
复制
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;
    }





}

汇编程序类:

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2018-09-26 01:10:36

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

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

首先通过添加"equals“和"hashCode”方法来修改实体(TestApi.java):

代码语言:javascript
复制
@Override
public int hashCode() {
   int hash = 0;
   hash += (sId != null ? sId.hashCode() : 0);
   return hash;
}

@Override
public boolean equals(Object object) {
    if (!TestApi.class.isAssignableFrom(object.getClass())) {
        return false;
    }
    TestApi other = (TestApi) object;
    return !(
        (this.sId == null && other.getsId() != null) 
        || (this.sId != null && !this.sId.equals(other.getsId()))
    );
}

这样,java.util.Set将能够在整个列表中创建一个distinct,然后修改您的TestController.java,使其返回一个集合而不是列表,如下所示:

代码语言:javascript
复制
@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);    
}

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

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

首先,您需要创建一个表示结果的接口,将您的TestRepo.java修改为:

代码语言:javascript
复制
@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);

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

代码语言:javascript
复制
public static interface UniqueTestApi {
    Long getSId();
    String getSName();
    String getCustRefId();
}

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

代码语言:javascript
复制
@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;    
}
票数 2
EN

Stack Overflow用户

发布于 2018-09-26 01:27:37

您可以使用Java 8 Streams将其过滤为一个集合:

代码语言:javascript
复制
Set<TestApi> filteredSet = testApiList.stream()
.collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TestApi::getSId))));

如果您想将其保留为列表,还可以使用Java 8的另一个特性:

代码语言:javascript
复制
//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;
    });

编辑

添加了重复列表。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52503150

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档