kosta 클라우드 네이티브 애플리케이션 개발 과정 day 17
array, list, set 을 이용한 lotto number 생성 예제
package kosta.mission3.mission3_02.lectureSolution;
import java.util.*;
public class LottoMain {
public static void main(String[] args) {
}
private static void lottoWithSet() {
Random random = new Random();
Set<Integer> set = new TreeSet<>();
for (int i =0; set.size() < 6; i ++){
set.add(random.nextInt(45) + 1);
}
System.out.println(set);
}
private static void lottoWithList() {
Random random = new Random();
List<Integer> list = new ArrayList<>();
while (true) {
int number = random.nextInt(45) + 1;
if (list.contains(number)) {
continue;
} else {
list.add(number);
}
if (list.size() == 6) {
break;
}
Collections.sort(list);
System.out.println(list);
}
}
private static void lottoWithArray() {
Random random = new Random();
int[] randomNumbers = new int[6];
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = random.nextInt(45);
for (int j = 0; j < i; j++) {
if (randomNumbers[i] == randomNumbers[j]) {
i--;
}
}
}
}
}
객체를 이용한 풀이
functional interface
package kosta.mission3.mission3_02.Lotto;
@FunctionalInterface
public interface RandomNumberGenerator {
int generateRandomNumber();
}
lotto number generator
package kosta.mission3.mission3_02.Lotto;
public class LottoNumberGenerator implements RandomNumberGenerator{
private static final int RANDOM_LOWER_INCLUSIVE = 1;
private static final int RANDOM_UPPER_INCLUSIVE = 45;
@Override
public int generateRandomNumber() {
return (int) (Math.random() * RANDOM_UPPER_INCLUSIVE ) + RANDOM_LOWER_INCLUSIVE;
}
}
lotto machine
package kosta.mission3.mission3_02.solution2;
import kosta.mission3.mission3_02.Lotto.LottoNumberGenerator;
import java.util.ArrayList;
import java.util.List;
public class LottoMachineSolution2 {
private List<LottoSolution2> lottoSolution2s = new ArrayList<>();
private final LottoNumberGenerator lottoNumberGenerator;
public LottoMachineSolution2(LottoNumberGenerator lottoNumberGenerator) {
this.lottoNumberGenerator = lottoNumberGenerator;
}
public void generateLotto(){
lottoSolution2s.add(LottoSolution2.of(lottoNumberGenerator));
}
public List<LottoSolution2> getLottoSolution2s() {
return lottoSolution2s;
}
}
로또 클래스 (구조적 방법과 함수형 방법을 같이 넣어봄)
package kosta.mission3.mission3_02.solution2;
import kosta.mission3.mission3_02.Lotto.LottoNumberGenerator;
import java.util.*;
import java.util.stream.Stream;
public class LottoSolution2 {
private static List<Integer> lotto = new ArrayList<>();
public LottoSolution2(List<Integer> lotto) {
this.lotto = lotto;
}
public static LottoSolution2 of(LottoNumberGenerator lottoNumberGenerator) {
// // struture way
Set<Integer> lottoNumbers = new TreeSet<>();
while (lottoNumbers.size() != 6) {
int numberGenerated = lottoNumberGenerator.generateRandomNumber();
lottoNumbers.add(numberGenerated);
}
// return new ArrayList<>(lottoNumbers);
// functional way
Stream.generate(lottoNumberGenerator::generateRandomNumber)
.limit(6)
.filter(v-> !lotto.contains(v))
.forEach((v)->lotto.add(v));
return new LottoSolution2(lotto);
}
public void show() {
System.out.println(Arrays.toString(lotto.toArray()));
}
}
팩토리 패턴으로 보다 클린하게 리팩토링
메인
package kosta.mission3.lottoWithFactory;
public class Main {
public static void main(String[] args) {
Lotto lotto1 = LottoMachine.createLotto();
Lotto lotto2 = LottoMachine.createLotto();
Lotto lotto3 = LottoMachine.createLotto();
Lotto lotto4 = LottoMachine.createLotto();
Lotto lotto5 = LottoMachine.createLotto();
lotto1.show();
}
}
로또 팩토리 (생성시 무한 스트림을 이용)
package kosta.mission3.lottoWithFactory;
import kosta.mission3.mission3_02.Lotto.LottoNumberGenerator;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
public class LottoMachine {
private static final LottoNumberGenerator lottoNumberGenerator = new LottoNumberGenerator();
public static Lotto createLotto(){
List<Integer> lottoNumbers = new ArrayList<>();
Stream.generate(lottoNumberGenerator::generateRandomNumber)
.filter(v-> !lottoNumbers.contains(v))
.limit(6)
.forEach(lottoNumbers::add);
return new Lotto(lottoNumbers);
}
}
로또 객체
package kosta.mission3.lottoWithFactory;
import java.util.Arrays;
import java.util.List;
public class Lotto {
private List<Integer> lottoNumbers;
public Lotto(List<Integer> lottoNumbers) {
this.lottoNumbers = lottoNumbers;
}
public void show() {
System.out.println(Arrays.toString(lottoNumbers.toArray()));
}
}
객체를 만들고 출력해보자 !
다양한 방식들
package kosta.mission3.mission3_03;
import java.util.*;
import java.util.stream.IntStream;
public class MemberMain {
public static void main(String[] args) {
// TODO : LIST를 생성해서 멤버 여러 개를 추가하고 전체를 출력하자.
List<Member> members = new ArrayList<>();
IntStream.range(0,10).forEach((i)->{
members.add(new Member(generateName(), i,"seoul"));
});
// printing 1
for (int i =0; i< members.size(); i++){
Member member = members.get(i);
System.out.println(member);
}
// printing 2
for (Member member : members) {
System.out.println(member);
}
// printing 3
Iterator<Member> iterator = members.iterator();
while(iterator.hasNext()){
Member member = iterator.next();
System.out.println(member);
}
// printing 4 - with lambda and stream
members.stream().forEach(member-> System.out.println(member));
// printing 5 - with stream and method referencing
members.forEach(System.out::println);
}
private static String generateName(){
Random random = new Random();
char[] name = new char[3];
IntStream.range(0,3).forEach((i)-> name[i] = (char) random.nextInt(97,122));
return Arrays.toString(name).replaceAll("[ ,\\[\\]]", "");
}
}
맵에 대해 알아보자 !
map : key와 value가 있을 때 => Map 인터페이스를 구현한
- hashMap
- LinkedHashMap
- treeMap
맵의 기본 제어 메서드
put : 넣는다
get : key 값으로 value를 가져온다
keySet() : 키 값만 추출
values() : Collection형태로 value 값을 가져온다
entrySet() : key, value 모두 추출 한다
스트림으로 모든 값을 출력하는 방법
System.out.println(Stream.of(ranks).collect(Collectors.toList()));
java의 collection이란 무엇일까?
First off: a List is a Collection. It is a specialized Collection, however.
A Collection is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.
A List adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.
In a Collection you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.
There are other specialized Collections as well, for example a Set which adds the feature that it will never contain the same element twice.
즉, list는 콜렉션이지만 order 기능이 구현된 것이다. (sort는 x)
collection vs collections
collecion : 인터페이스
collecitons : utitliy class
stack 과 queue에 대해 간단히 알아보자 .
stack => 예시 : 뒤로가기, 괄호
queue => 예시 : 주문
스택을 활용한 괄호 풀기 예제
package kosta.basic.day017.stackAndQueue;
import java.util.Scanner;
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
// 키보드로부터 수학 수식을 입력
// ((2+3)+10) => 괄호 일치 여부 판단
Scanner scanner = new Scanner(System.in);
while (true) {
Stack<Character> stack = new Stack<>();
System.out.print("수식 입력: ");
String word = scanner.nextLine();
try {
for (int i = 0; i < word.length(); i++) {
char alphabet = word.charAt(i);
if (alphabet == '(') {
stack.push(alphabet);
continue;
}
if (alphabet == ')') {
stack.pop();
}
if (stack.isEmpty()) {
System.out.println("수식 일치 !");
continue;
}
System.out.println("수식 일치 안함 !");
}
} catch (Exception ignored) {
System.out.println("수식 일치 안함 !");
}
}
}
}
정렬
comparator를 통한 구현
package kosta.basic.day017.sort;
import java.util.Comparator;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
class descendingComparator implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
return Integer.compare(o1, o2);
}
}
public class Main {
public static void main(String[] args) {
// Arrays.sort(배열) -> 오름차순
// List -> 입력순서 -> 정렬순서
// Collections.sort( 리 스 트 )
// Comparable -> compareTo 로 정렬 기준을 세우기 // 객체에서는 comparable을 구현하여 override
// Comparator -> compare() // comparator를 만들 경우는 comparator를
Random random = new Random();
Set<Integer> treeSet = new TreeSet<>(new descendingComparator());
Set<Integer> treeSet2 = new TreeSet<>(Integer::compare);
for (int i = 0; i < 10; i++) {
treeSet.add(random.nextInt(45) + 1);
treeSet2.add(random.nextInt(45) + 1);
}
System.out.println(treeSet);
System.out.println(treeSet2);
}
}
Comparable -> compareTo 로 정렬 기준을 세우기
// 객체에서는 comparable을 구현하여 override => 최초의 정렬 기준을 세워줌
// Comparator -> compare()
// comparator를 만들 경우는 comparator를
음식점 과제를 풀어보자 !
main
package kosta.mission3.mission3_04;
public class Main {
public static void main(String[] args) {
// 1. 주문요청 2. 주문처리 3. 매출액 총액 4. 종료
// 입력 1 -> Food(foodName, price), Order(Food, amount) 생성 => 자료 구조 추가
// 입력 2 -> 자료구조에 있는 주문처리 (주문된 내용 출력)
// 입력 3 -> 주문처리된 메뉴에 대한 합계 출력
Store.openStore();
DeliveryManager deliveryManager = new DeliveryManager();
deliveryManager.receive(new Order());
deliveryManager.receive(new Order());
deliveryManager.receive(new Order());
deliveryManager.receive(new Order());
deliveryManager.receive(new Order());
deliveryManager.handleOrder();
}
}
store
package kosta.mission3.mission3_04;
import java.util.ArrayList;
import java.util.List;
public class Store {
public static List<Food> foods = new ArrayList<>();
public static void createFood(String foodName, int price) {
foods.add(new Food(foodName, price));
}
public static void openStore() {
Store.createFood("참치김밥", 3500);
Store.createFood("불고기김밥", 4000);
Store.createFood("라면", 4500);
Store.createFood("김치볶음밥", 5500);
Store.createFood("짜장면", 4300);
Store.createFood("더블비트트칠리버거", 9500);
Store.createFood("블랙어니언와퍼", 8900);
showOpenMessage();
}
private static void showOpenMessage() {
System.out.print(String.format("""
<객체킹 음식점>
메뉴 종류 : %s
""", retrieveFoodsNowSelling()));
}
private static String retrieveFoodsNowSelling() {
StringBuilder stringBuilder = new StringBuilder();
foods.forEach(food -> stringBuilder.append(food.getName()).append(" "));
return stringBuilder.toString();
}
}
delivery manager
package kosta.mission3.mission3_04;
import java.util.LinkedList;
import java.util.List;
public class DeliveryManager {
private static final List<Order> orders = new LinkedList<>();
public DeliveryManager() {
}
public void receive(Order order) {
orders.add(order);
}
public void handleOrder() {
confirmOrders();
showReceipt();
}
private void confirmOrders() {
System.out.println("\n주문 내역입니다 ^ㅡㅡㅡㅡ^\n");
orders.forEach(order -> {
int price = Store.foods.stream()
.filter(v -> v.getName().equals(order.getFoodRequested()))
.findFirst()
.get()
.getPrice();
System.out.printf("%s %s \n", order.getFoodRequested(), price);
}
);
InputView.requestConfirm();
}
private void showReceipt() {
int total = orders.stream().mapToInt(order -> {
return Store.foods.stream()
.filter(food -> food.getName().equals(order.getFoodRequested()))
.mapToInt(Food::getPrice)
.sum();
}).sum();
System.out.printf("\n전체 가격 %s원 입니다! 맛 점 하 세 요 !\n", total);
}
}
food
package kosta.mission3.mission3_04;
public class Food {
private String name;
private int price;
public Food(String name, int price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public int getPrice() {
return price;
}
}
order
package kosta.mission3.mission3_04;
import java.util.Scanner;
public class Order {
public static final Scanner SCANNER = new Scanner(System.in);
private final String foodRequested;
public Order() {
this.foodRequested = InputView.requestOrder();
}
public String getFoodRequested() {
return foodRequested;
}
}
input view
package kosta.mission3.mission3_04;
import java.util.Scanner;
public class InputView {
private static final Scanner SCANNER = new Scanner(System.in);
public static String requestOrder() {
System.out.print(String.format("""
메뉴를 고르세요: %s""", " "));
return SCANNER.nextLine().trim();
}
public static String requestConfirm(){
System.out.println("\n주문 확인 부탁드릴게요! 맞다면 1번 눌러주세요오오오 :)");
return SCANNER.nextLine().trim();
}
}
'교육 > Java&Spring' 카테고리의 다른 글
kosta 클라우드 네이티브 애플리케이션 개발 과정 day 19 (0) | 2023.01.13 |
---|---|
kosta 클라우드 네이티브 애플리케이션 개발 과정 day 18 (0) | 2023.01.13 |
kosta 클라우드 네이티브 애플리케이션 개발 과정 day 16 (0) | 2023.01.10 |
kosta 클라우드 네이티브 애플리케이션 개발 과정 day 15 (0) | 2023.01.09 |
kosta 클라우드 네이티브 애플리케이션 개발 과정 day 14 (0) | 2023.01.06 |