2013-06-10 1 views
2

안녕하세요 자바의 ArrayList에서 항목을 누락 및 징수 부분에 내 손을 시도하고 있었다 찾기, 내가 두 배열 목록의이 직원 개체나는 자바에 안돼서

class Employee 
{ 
    private int emp_id; 
    private String name; 
    private List<String> mobile_numbers; 

    //.....getters and setters 
} 

listA라고 말하고 간단한 쿼리 이 listBlistOfMobileNumbers는 이제 List<String>

있는 다음 데이터

List<Employee> listA = new ArrayList<Employee>(); 
    List<Employee> listB = new ArrayList<Employee>(); 

    listA.add(new Employee("101", "E1", listOfMobileNumbers)); 
    listA.add(new Employee("102", "E2", listOfMobileNumbers1)); 
    listA.add(new Employee("103", "E3", listOfMobileNumbers2)); 
    listA.add(new Employee("104", "E4", listOfMobileNumber4)); 
    listA.add(new Employee("105", "E5", listOfMobileNumbers5)); 

    listB.add(new Employee("101", "E1", listOfMobileNumbers1)); 
    listB.add(new Employee("102", "E2", listOfMobileNumbers2)); 
    listB.add(new Employee("106", "E6", listOfMobileNumber6)); 
    listB.add(new Employee("107", "E7", listOfMobileNumber7)); 
    listB.add(new Employee("108", "E8", listOfMobileNumbers8)); 

이 개인 목록에서 추가 요소를 찾고 싶습니다. 예 :

List<Employee> additionalDataInListA = new ArrayList<Employee>(); 
    // this list should contain 103, 104 and 105 

    List<Employee> additionalDataInListB= new ArrayList<Employee>(); 
    // this list should contain 106, 107 and 108    

어떻게하면됩니까?

귀하의 도움에 감사드립니다.

편집 : 나는 내가 비교 함수의 일부 수동 기능의 종류를 쓰고 그것을 달성하려는 내부 기능을 사용하지 않으

. 내 유스 케이스에 내가 int이며 FieldNoList<String>입니다 때문에

나는 또한 동등한 기능을 무시하지 못할.

필드의 발생은 'n'번이고 해당 필드와 연결된 값이 다를 때마다 발생합니다.

예 : FieldNo = 18 값 = [ "A"];

FieldNo = 18 값 = [ "B"]; 등등 ...

내가 사용한 직원 ID는 같음과 해시 코드를 덮어 쓰는 것이 중요합니다.

+2

지금까지 시도한 것은 무엇입니까? '종업원'을 비교해 봤어? 반복을 목록을 통해 완료 했습니까? – thegrinner

+0

가능한 복제본 [자바에서 유니온, 교차, 차이 및 리버스 데이터의 방법] (http://stackoverflow.com/questions/3590677/how-to-union-intersect-difference-and-reverse-data-in-java)) –

+0

@ user2437809 lambdaj 및 hamcrest 라이브러리를 사용하여 내 솔루션을 참조하십시오 (몇 줄에서 수행 할 수 있음). –

답변

-1
for(int j = 0; j < listB.size(); j++){ 
    if (!listA.contains(listB.get(j)) 
     additionalDataInListB.add(listB.get(j)) 
} 

반대의 값을 사용하여 additionalDataInListA 객체를 채우기 만하면됩니다. 이것은 트릭을해야합니다 :)

EDIT : 이것들은 같은 객체 일 때만 작동합니다. 그것은 사실이 아닐 수도 있습니다. 이것이 사실이 아니라면, 아마도 emp_id와 같은 특성 중 하나를 비교하여 그 특성이 동일한 지 확인해야합니다. 일치하지 않으면 다른 목록에 새 목록을 추가하십시오.

+1

contains는'Employee'에서'equals'를 오버라이드하는 경우에만 작동합니다. –

+0

'equals'가 employee id만으로 구현되지 않았다면 이것은 작동하지 않을 것입니다. –

+0

equals가 구현되어 있지만 api 메소드가 선호되는 경우이 함수가 작동합니다. – tgkprog

2

무시 equals는 ID 사이에 평등 테스트 (당신은 equals를 오버라이드 (override) 할 경우에 당신은 또한 hashCode를 오버라이드 (override) 할 필요가 기억)합니다.그런 다음 :

List<Employee> additionalDataInListA = new ArrayList<Employee>(listA); 
additionalDataInListA.removeAll(listB); 

List<Employee> additionalDataInListB = new ArrayList<Employee>(listB); 
additionalDataInListB.removeAll(listA); 

관련 문서 :

2

당신은 boolean removeAll(Collection<?> c) 방법을 사용할 수 있습니다.

이 메서드는 사용자가 호출하는 List을 수정합니다. 경우 원래의 List 유지하는 경우 다음 복사본의 복사본을 먼저 목록의 복사본을 만들어야 할 것입니다.

List<Employee> additionalDataInListA = new ArrayList<Employee>(listA); 
additionalDataInListA.removeAll(listB); 
+0

'equals()'및'hashCode()'가'Employee' 클래스에서 재정의되어야합니다. – GriffeyDog

+0

@GriffeyDog : 컬렉션이 제대로 작동하려면 개체가 충족시켜야하는 기본 요구 사항이 맞습니다. –

0
class Employee { 
    private int empId; 
    ... 
    @Override 
    public int hashCode() { return empId; } 

    @Override 
    public boolean equals(Object other) { 
     return other != null && other instanceof Employee && other.empId == empId; 
    } 
} 

당신이 Set<Employee> employees = new HashSet<Employee>() 수 있도록 허용합니다.

세트는 removeAll 및 retainAll과 같은 설정 작업을 수행 할 수 있습니다.

최적 일 것입니다 (List에서는 그렇지 않습니다).

1

당신은 lambdaj (download here, website)과 hamcrest (download here, website)를 사용할 수 있습니다,이 라이브러리 컬렉션을 관리하기위한 매우 강력하며, 다음 코드는 매우 간단하고 완벽하게 작동합니다. 이 라이브러리를 사용하면 한 줄로 문제를 해결할 수 있습니다. 프로젝트에 hamcrest-all-1.3.jar 및 lambdaj-2.4.jar을 추가해야합니다. 도움이 필요하십니까?

import static ch.lambdaj.Lambda.filter; 
import static ch.lambdaj.Lambda.having; 
import static ch.lambdaj.Lambda.on; 
import java.util.Arrays; 
import java.util.List; 
import static org.hamcrest.Matchers.isIn; 
import static org.hamcrest.Matchers.not; 

public class Test2{ 
     public static void main(String[] args) { 
      List<String> oldNames = Arrays.asList("101","102","103","104","105"); 
      List<String> newNames = Arrays.asList("101","102","106","107","108"); 

      List<String> newList = filter(not(having(on(String.class), isIn(oldNames))),newNames); 
      List<String> newList2 = filter(not(having(on(String.class), isIn(newNames))),oldNames); 
      System.out.println(newList); 
      System.out.println(newList2); 
      /*out 
      [106, 107, 108] 
      [103, 104, 105] 
      */ 
    } 
} 

이 예제는 간단한 문자열 목록과 작동하지만 개체에 맞게 조정할 수 있습니다. 직원.

0

매우 간단합니다. 먼저 배열을 반복하고 모든 숫자의 합계를 구합니다. 1에서 n까지의 자연수 합계를 알기 때문에 n * (n + 1)/2로 쓸 수 있습니다. 이제 우리는 [n * (n + 1)/2]에서 배열의 합을 빼야합니다.

여기에 누락 된 전화 번호가 표시됩니다.

코드에서이 논리를 구현할 수 있습니다.

Source with example