글을 쓰게 된이유

부끄럽지만 자바8를 올해 처음으로 배우게 되어 써먹는중이다. 그것도 나의 의지가 아닌 PM이 자바8를 선호하기에 억지로 쓰는중이지만.... 매우 유용하고 코드가 간결해진다는 걸 많이 느낀다. 

 

코드가 쓰인곳

어떤 상품정보를 등록할 수 있으며 수정할 수 있는 서비스가 있었다.

하나의상품의 디테일을 들어가 수정할 때 다른상품의 정보도 변경할 수 있기에

하나의 상품만 수정이 일어날 때 모든 상품의 정보가 서버에 넘어가게 된다. 정말 편하게 모든 상품을 update 해버리면 편하지만....

만약 상품이 만개라면... 만개가 전부 업데이트 쳐지는 정말 이상한 일이 일어난다....

그 때 antMatch()를 사용하여 수정된 아이템들 만 걸러내어 db의 update가 일어난다. 만개중 2개만 수정되었다면

두개의 정보만 update된다.

 

예제

간단하게 상품(goods) 안에는 상품이름(name), 가격(price) 정보가 있다고 가정하여 예제를 작성하였다.

System.out.println() 처음 쓰인곳 전에는 전부 예제를 만들기 위한 코드이다 무시해도된다.

package test;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Random;
import java.util.stream.Collectors;

import test.StreamTest.User;

public class Goods {

	String goodsName;
	int price;
	
	
	
	public Goods(String goodsName, int price) {
		super();
		this.goodsName = goodsName;
		this.price = price;
	}
	
	public String getGoodsName() {
		return goodsName;
	}
	public void setGoodsName(String goodsName) {
		this.goodsName = goodsName;
	}
	public int getPrice() {
		return price;
	}
	public void setPrice(int price) {
		this.price = price;
	}
	
	public static Goods createUser() {
		
		String[] first = {"가","나","다","라","마","바","사","아","자","차","카"};
		String[] second = {"가","나","다","라","마","바","사","아","자","차","카"};
		String[] third = {"가","나","다","라","마","바","사","아","자","차","카"};
		int cnt = 0;
		String name = "";
		int price = 0;
		while(cnt < 3) {
			Random index = new Random();
			name = name + first[index.nextInt(10)];
			price = cnt * index.nextInt(10);
			cnt++;
		}
		
		return new Goods(name, price);
	}
	
	public static void main(String[] args) {
		
		int cnt = 0;
		List<Goods> goodList = new ArrayList();
		List<Goods> dbList = new ArrayList();
		while(cnt < 10) {
			Goods goods= createUser();
			List<Goods> find = goodList.stream()
					.filter(list -> Objects.equals(list.getGoodsName(), goods.getGoodsName()))
					.collect(Collectors.toList());
			
			if(find.size() == 0) {
				goodList.add(goods);
				if(cnt%2 == 0) {
						Goods newUser = new Goods(goods.getGoodsName(),2*cnt);
						dbList.add(newUser);
						
				} else {
					dbList.add(goods);
				}
				cnt++;
			} 
		}
		
		System.out.println("=========================randomList=====================================");	
		goodList.stream().forEach(list -> System.out.println(list.getGoodsName() + "  " + list.getPrice()));
		System.out.println("=========================DBList=========================================");	
		dbList.stream().forEach(list -> System.out.println(list.getGoodsName() + "  " + list.getPrice()));
		
		
		System.out.println("==============================anyMatch()==========================================");	
		
		goodList.stream()
		.filter(randomList -> !dbList.stream()
			.anyMatch(db -> randomList.getGoodsName().equals(db.getGoodsName())  && randomList.getPrice() == db.getPrice())
		).forEach(add -> System.out.println(add.getGoodsName() + "   "+ add.getPrice()));;
		
		

	}
	
}

 

리스트와 리스트중 비교해서 다른것 찾기 

위 코드를 돌리면 아래와 같이 콘솔에 찍인다.

randomList가 view 단에서 넘어온 수정된것과 안된 모든 상품리스트이다.

DBList 가 수정이 안된 모든 상품리스트다.

anyMatch() 는 dbList정보와 다른 randomList 상품정보이다.

anyMatch() 를 사용하고 filter 조건문에 ! 를 사용하여  상품이름과 가격중 하나라도 db정보와 틀린데이터는 forEach 문에 들어오게된다. forEach문에 업데이트쿼리를 타게끔하면 된다. 

goodList.stream()
.filter(randomList -> dbList.stream()
    .noneMatch(db -> randomList.getGoodsName().equals(db.getGoodsName())  && randomList.getPrice() == db.getPrice())
).forEach(add -> System.out.println(add.getGoodsName() + "   "+ add.getPrice()));;

반대로 ! 를 사용하지않고 그냥 noneMatch 를 사용해도 같은결과가 나온다.

=========================randomList=====================================
차차자  8
사사차  4
나가자  8
마나차  18
바다자  4
가가마  6
다사차  2
마다마  2
나다다  18
라바나  4
=========================DBList=========================================
차차자  0
사사차  4
나가자  4
마나차  18
바다자  8
가가마  6
다사차  12
마다마  2
나다다  16
라바나  4
==============================anyMatch()==========================================
차차자   8
나가자   8
바다자   4
다사차   2
나다다   18
복사했습니다!