有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java根据匹配Id检索单个记录

我在Set中存储了一些ID,在此基础上,我想从ArrayList中检索单个记录,我尝试了很多方法,找到了一种方法,获取匹配元素的索引,然后调用list.get()方法来获取单个记录

每当我调用indexOf(),它总是返回-1,但是元素出现在列表中

public String checkIsHoldingMemberSelected(){
    String result = AppConstants.NO_HOLDING_MEMBER_SELECTED;
    JSONObject json = new JSONObject();
    List<Account>selectedMemberList=new ArrayList<Account>();
    try{
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpSession httpSession = request.getSession();
        if(null != httpSession.getAttribute(AppConstants.SEARCH_HOLDING_MEMBER_IDS)){
            Set<String> smId = (HashSet<String>)httpSession.getAttribute(AppConstants.SEARCH_HOLDING_MEMBER_IDS);
            if(!smId.isEmpty()){
                List<Account>holdingMemberList=(List<Account>) httpSession.getAttribute("memberList");
                for(String memberId:smId) {
                    int index=holdingMemberList.indexOf(memberId);
                    selectedMemberList.add(holdingMemberList.get(index));
                }
                result = AppConstants.SELECTED; 
            }
        }
        json.put("result", result);
        writeJSONData(json);
    }catch(Exception e){
        e.printStackTrace();
    }
    return null;
}

我不知道这个方法是否好,请建议我好的方法,我的简单要求是,我有Set,其中我们有像100110021003这样的成员ID

现在我想在holdingMemberList中找到这些ID,如果有匹配项,那么我只需要整个记录并添加到另一个列表中


共 (2) 个答案

  1. # 1 楼答案

    虽然建议的方法有效,但最终可能会多次迭代ArrayList

    更好的方法是迭代ArrayList一次,然后检查Set.contains()这样的Id。如果是,则将其添加到结果中。这样,您只需迭代整个ArrayList一次

    List<Account> selectedMemberList= new LinkedList<>();
    for(Account member: holdingMemberList) {
      if(smId.contains(member) {  //seems like you have overridden the equals() already
        selectedMemberList.add(member);
      }
    }
    
    
  2. # 2 楼答案

    问题indexOf只能在整个帐户上工作,然后对象仍然应该是equals一对一。因此,您必须从每个帐户获取成员ID

            Set<String> smId =
                   (Set<String>) httpSession.getAttribute(AppConstants.SEARCH_HOLDING_MEMBER_IDS);
            if (!smId.isEmpty()) {
                List<Account> holdingMemberList =
                        (List<Account>) httpSession.getAttribute("memberList");
                for (Account account : holdingMemberList) {
                    if (smId.contains(account.getMemberId())) {
                        selectedMemberList.add(account);
                    }
                }
                result = AppConstants.SELECTED; 
            }
    

    for循环也可以使用较新的Stream类完成,例如:

                List<Account> selected = holdingMemberList.stream()
                        .filter(act -> smId.contains(act.getMemberId())
                        .collect(Collectors.toList());
                selectedMemberList.addAll(selected);