01. Java (v)
02. git
03. Database
04. Jsp [Server]
05. 미니프로젝트 (3W)
06. HTML,CSS
07. JS
08. SpringFramework , SrpingBoot
09. React JS [Front-end]
10. 중간프로젝트 (1M)
11. Linux 명령어
12. AWS 클라우드
13. DevOps - Docker
14. App - Android
15. 최종프로젝트 (1M)
컬렉션의 저장 요소를 하나씩 참조하도록 도와주는 반복자
람다식으로 처리할 수 있도록 해주는 반복자
파일 입출력 stream과는 다른 개념
List<String> list = Arrays.asList("홍길동","이순신","홍길자","신사임당");
for(String s:list) {
System.out.println(s);
}
System.out.println("-".repeat(30));
// 람다스트림 사용 시
Stream<String> stream = list.stream();
// 익명자 사용
//stream.forEach(new Consumer<String>() {
//
// @Override
// public void accept(String t) {
// System.out.println(t);
// }
//});
stream.forEach(s->System.out.println(s));
List<Integer> list = new ArrayList<>();
for(int i=0;i<100;i++) {
list.add(new Random().nextInt(100)+1); // 1~100 랜덤수
}
System.out.println(list.toString());
System.out.println("-".repeat(100));
// 중복제거 distinct
// 정렬 sorted
list.stream().sorted().forEach(a->System.out.println(a));
System.out.println("-".repeat(100));
list.stream().distinct().forEach(a->System.out.println(a));
System.out.println("-".repeat(100));
list.stream()
.distinct()
.sorted((o1,o2)->Integer.compare(o2, o1)) // 내림차순
.forEach(a->System.out.print(a+" "));
System.out.println("\n"+"-".repeat(100));
// 걸러내기 filter함수
// boolean타입을 반환하며 true인 값만 필터링
list.stream().filter(a->a%2==0).forEach(a->System.out.print(a+" "));;
System.out.println("\n"+"-".repeat(100));
// 새로운 stream으로 반환 map
// 원본리스트의 값이 50보다 큰 값이면 true, 아니면 false
list.stream().map(a-> a>=50).forEach(a->System.out.print(a+" "));
System.out.println("\n"+"-".repeat(100));
// 스트림의 형변환 mapTo~~
list.stream().mapToDouble(a->a-20).forEach(a->System.out.print(a+" ")); // double형으로 변환
// 최종처리 집계함수 max, min, sum ,count, average
int max = list.stream().mapToInt(a->a).max().getAsInt();
int min = list.stream().mapToInt(a->a).min().getAsInt();
long count = list.stream().mapToInt(a->a).count();
double avg = list.stream().mapToInt(a->a).average().getAsDouble();
int sum = list.stream().mapToInt(a->a).sum();
System.out.println("리스트에서 max값:"+max);
System.out.println("리스트에서 min값:"+min);
System.out.println("리스트에서 count값:"+count);
System.out.println("리스트에서 max값:"+max);
System.out.println("리스트에서 평균:"+avg);
System.out.println("리스트에서 합계:"+sum);
System.out.println("\n"+"-".repeat(100));
// 최종처리 수집함수 collect - 컬렉션 타입으로 변환
// 50보다 큰 값들만 list로 다시 얻는다
// 리스트로 변환
List<Integer> newList=list.stream().filter(a->a>=50).collect(Collectors.toList());
System.out.println(newList.toString());
System.out.println("\n"+"-".repeat(100));
// 맵으로 변환
Map<Integer,Integer> newMap=list.stream().distinct().filter(a->a>=50).collect(Collectors.toMap(a->a,a->a*a));
System.out.println(newMap.toString());
System.out.println("\n"+"-".repeat(100));
// 리스트의 요소들 중에서 4글자 이상인 값만 남기고,전부 대문자로 바꾸고, 알파벳순으로 정렬한 결과를 새로운 리스트로 반환
List<String> names = Arrays.asList("hong","kim","park","choi","an");
List<String> nameList = names.stream().filter(a->a.length()>=4).map(a->a.toUpperCase()).sorted((o1,o2)->o1.compareTo(o2)).collect(Collectors.toList());
System.out.println(nameList.toString());
종류
수직선(|)
: 항목들 중 하나를 선택하기 위해 구분 ex) gray|grey
-> gray 또는 grey와 일치
괄호(())
: 연산자의 범위와 우선순위 지정
물음표(?)
: 0번 또는 1번까지의 발생 의미 ex) colou?r
-> color와 colour 둘다 일치
별표(*)
: 0번 이상의 발생 의미 ex) ab*c
-> ac / abc / abbc / abbbc / ....
덧셈기호(+)
: 1번 이상의 발생 의미 ex) ab+c
-> abc / abbc / abbbc
{n}
: 정확히 n번만큼 일치
{m,}
: m번 이상만큼 일치
{m,n}
: m번 이상 n번 이하만큼 일치 ex) a{1,3}b
-> ab /aab /aaab
.
: 문자 한 개와 일치
[ ]
: 여러 문자들 중 하나의 문자와 일치 ex) [0-9]
-> 0 - 9 / [a-z] -> a - z
String info="홍길자|30|서울시 강남구|010-1234-4567";
// 전화번호 형식만 찾아서 **** 암호처리
String pattern="[0-9]{3}-[0-9]{3,4}-[0-9]{4}";
String result=info.replaceAll(pattern, "***-****-****");
System.out.println(result);
[^ ]
: 해당 문자들을 포함하지 않는 문자들을 찾음^
: 처음 시작하는 부분 의미$
: 끝나는 부분 의미( )
: 하위 식 정의₩w
: "-"를 포함한 영문자와 숫자 일치₩W
: "-"와 영문자 그리고 숫자를 제외한 다른 문자열들을 일치₩s
: 공백 문자와 일치₩S
: 공백을 제외한 어떤 것이든 일치₩d
: 숫자와 일치₩D
: 숫자가 아닌 항목을 일치 String info = "30세/홍길동/강남구/02-123-1234/010-1234-1234/aaA334@example.com";
String pattern1="\\d{2,3}-\\d{3,4}-\\d{4}";
Pattern p1=Pattern.compile(pattern1);
Matcher m1= p1.matcher(info); // 적용할 문자열을 넣는다.
/* Mathcer 메서드
*
* find - 정규표현식을 찾음(찾으면 true, 없으면 false)
* group - 정규표현 문자열을 얻음
* start - 시작 위치
* end - 끝 위치
*/
while(m1.find()) { // 1번 수행시에 앞에서 한번 찾음
System.out.println("정규표현식에 해당하는 문자를 찾음");
System.out.println(m1.group());
System.out.println("시작 위치 : "+m1.start());
System.out.println("끝 위치 : "+m1.end());
}
System.out.println("-".repeat(30));
// 이메일 형식
String pattern2 = "[a-zA-Z0-9]+@[a-z]+\\.[a-z]+";
Pattern p2 = Pattern.compile(pattern2);
Matcher m2 = p2.matcher(info);
while(m2.find()) {
System.out.println("정규표현식에 해당하는 문자를 찾음");
System.out.println(m2.group());
System.out.println("시작 위치 : "+m2.start());
System.out.println("끝 위치 : "+m2.end());
}
String str = "헐4,500원 일수도 있고~ 1,200원 일수도 있지. 하지만 가격은 6000원 일 수도 있어";
String pattern="\\d+원|\\d+(,\\d+)*원";
Pattern p = Pattern.compile(pattern);
Matcher m = p.matcher(str);
while(m.find()) {
System.out.println(m.group());
}
방법1
public class ThreadTest implements Runnable{
// 1. runnable 인터페이스를 상속받아서 사용하는 방법
int num=0;
@Override
public void run() {
// TODO Auto-generated method stub
for(int i=1;i<=10;i++) {
if(Thread.currentThread().getName().equals("A")) {
}
num++;
System.out.println(Thread.currentThread().getName() + "num값:"+num);
// 일시정지
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
// main클래스
public class MainClass {
public static void main(String[] args) {
// 메인스레드
// 객체 1개를 쓰레드 n개로 실행 - 동시성의 문제가 생길수 있음
ThreadTest th = new ThreadTest();
Thread thread = new Thread(th,"A");
Thread thread2 = new Thread(th,"B");
thread.start();
thread2.start();
try {
thread.sleep(1000);
System.out.println("메인 쓰레드 출력");
}
catch(InterruptedException e) {
e.printStackTrace();
}
}
}
방법2
public class ThreadTest extends Thread {
// 1. thread클래스를 상속받아서도 사용 가능
// - 클래스가 전부 쓰레드기능을 가지게 됨
@Override
public void run() {
for(int i=1;i<=10;i++) {
System.out.println(getName()+", "+i);
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// main클래스
public class MainClass2 {
public static void main(String[] args) {
// N개의 객체, N개의 쓰레드로 각자 실행
ThreadTest th1 = new ThreadTest();
ThreadTest th2 = new ThreadTest();
Thread thread1 = new Thread(th1,"A");
Thread thread2 = new Thread(th2,"B");
thread1.start();
thread2.start();
System.out.println("메인쓰레드 종료");
}
}
메서드
start()
(static)currentThread()
getNmae()
sleep()
yield()
// A클래스스
public class TestA implements Runnable{
public boolean worker = true;
@Override
public void run() {
while(true) {
if(worker) {
System.out.println("스레드 A가 실행중");
}else {
// 실행양보 - 다른 쓰레드에게 실행 양보
Thread.yield();
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
// B클래스
public class TestB implements Runnable{
@Override
public void run() {
while(true) {
System.out.println("스레드 B 실행중");
try {
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
// main클래스
public class MainClass {
public static void main(String[] args) {
TestA a =new TestA();
TestB b = new TestB();
Thread thread1 = new Thread(a,"A");
Thread thread2 = new Thread(b,"B");
thread1.start();
thread2.start();
try{
Thread.sleep(3000);
a.worker=false;
Thread.sleep(10000);
a.worker=true;
}catch(Exception e) {
}
}
}
join()
// A클래스
public class TestA implements Runnable{
public int sum = 0;
@Override
public void run() {
//1~100까지의 누적 합
for(int i=1;i<=100;i++) {
sum+=i;
System.out.println("A현재누적합:"+sum);
try {
Thread.sleep(100);
}catch(Exception e) {
}
}
}
}
// main클래스
public class MainClass {
public static void main(String[] args) {
TestA a = new TestA();
Thread thread = new Thread(a);
thread.start();
// 이 스레드가 종료될 때까지 다른 스레드를 정지
try {
thread.join();
} catch (Exception e) {
}
System.out.println("A스레드의 계산결과:"+a.sum);
System.out.println("메인스레드 종료");
}
}
동기화 메서드 synchronized
public class ThreadTest implements Runnable{
// 1. runnable 인터페이스를 상속받아서 사용하는 방법
// synchronized - 쓰레드가 동기화메서드를 점유할 때, 다른 쓰레드의 침범을 막음
int num=0;
@Override
public synchronized void run() {
// TODO Auto-generated method stub
for(int i=1;i<=10;i++) {
if(Thread.currentThread().getName().equals("A")) {
num++;
}
System.out.println(Thread.currentThread().getName() + "num값:"+num);
// 일시정지
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}