Java stream을 이용한 ArrayList 처리.
중복제거 : distinct()
List<Integer> listWithDuplicates = Lists.newArrayList(1, 1, 2, 2, 3, 3); List<Integer> listWithoutDuplicates = listWithDuplicates.stream() .distinct() .collect(Collectors.toList());
2개의 List간의 중복데이터 추출 또는 제거
class Employee { Integer employeeId; String employeeName; // getters and setters } class Department { Integer employeeId; String department; // getters and setters } @Test public void FilteredCorrectly() { // 부서명이 sales이고, employeeId가 동일한 데이터만 추출 List<Employee> filteredList = emplList.stream() .filter(empl -> deptList.stream() .anyMatch(dept -> // 1개라도 일치하는 게 있으면 true를 반환한다. dept.getDepartment().equals("sales") && empl.getEmployeeId().equals(dept.getEmployeeId()))) .collect(Collectors.toList()); // 부서명이 sale 이고, employeeId가 동일한 데이터는 모두 제거 List<Employee> filteredList = emplList.stream() .filter(empl -> deptList.stream() .noneMatch(dept -> // 일치하는 게 하나도 없으면 true를 반환한다. dept.getDepartment().equals("sales") && empl.getEmployeeId().equals(dept.getEmployeeId()))) .collect(Collectors.toList()); } // 참고 : https://www.baeldung.com/java-streams-find-list-items
2개의 List의 특정값을 기준으로 어느 한쪽의 List Merge
// Lombok 이용 @Data @NoArgsConstructor @AllArgsConstructor class Server { private String name; private String attribute1; private String attribute2; } public class listTest { @Test public void listMergeTest() throws Exception { List<Server> servers1 = Arrays.asList( new Server("name1", "attr1.1", null), new Server("name2", "attr1.2", null), new Server("name4", "attr1.3", null)); List<Server> servers2 = Arrays.asList( new Server("name1", null, "attr2.1"), new Server("name2", null, "attr2.2"), new Server("name3", null, "attr2.3") ); // servers2의 (name, attribute2) 형태의 맵을 미리 만들어 둔다. Map<String, String> mapping = servers2.stream().collect(Collectors.toMap(m -> m.getName(), m -> m.getAttribute2())); // servers1의 attribute2의 값을 앞에서 만든 맵핑 테이블을 이용하여 저장한다. servers1.stream().forEach(m -> m.setAttribute2(mapping.get(m.getName()))); System.out.println(servers1); } }
최신 댓글