티스토리에 저장했던 글을 옮겼습니다.
https://mrcocoball.tistory.com/91
public class IntArrayStreamTest {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
for (int num : arr) {
System.out.println(num);
}
System.out.println("스트림 적용");
Arrays.stream(arr).forEach(n -> System.out.println(n));
// Arrays.stream을 통해 IntStream 타입 값 반환 가능,
// forEach를 통해 arr의 요소를 하나하나 꺼내서 처리를 하는데 그 처리 내용은 n -> System.out.println(n)
IntStream is = Arrays.stream(arr);
System.out.println("1회차");
is.forEach(n -> System.out.println(n));
System.out.println("2회차");
// is.forEach(n -> System.out.println(n)); 스트림이 소모가 되어 Exception 발생, 스트림 재생성 필요!!
}
}
public class ArrayListStreamTest {
public static void main(String[] args) {
List<String> sList = new ArrayList<String>();
sList.add("리코");
sList.add("마리");
sList.add("요시코");
Stream<String> stream = sList.stream();
stream.forEach(s -> System.out.println(s));
sList.stream().sorted().forEach(s -> System.out.print(s + "\t")); // 요소를 정렬해서 출력
System.out.println();
sList.stream().map(s->s.length()).forEach(n -> System.out.print(n + "\t")); // 문자 길이를 출력
System.out.println();
sList.stream().filter(s->s.length()>=3).forEach(s -> System.out.print(s + "\t")); // 문자 길이가 3 이상인 요소 출력
}
}
T reduce (T identify, BinaryOperator<T> accumlator)
T reduce (T 초기값, BinaryOperator<T> accumlator)
Arrays.stream(arr).reduce(0, (a,b) -> a+b));
class CompareString implements BinaryOperator<String> {
@Override
public String apply(String s1, String s2) {
if (s1.getBytes().length >= s2.getBytes().length ) return s1;
else return s2;
}
}
public class ReduceTest {
public static void main(String[] args) {
String greetings[] = {"안녕하세요~~~", "Hello", "Goood Morning", "반가워요 참새콘"};
// 직접 람다식 사용
System.out.println(Arrays.stream(greetings).reduce("", (s1, s2) ->
{if (s1.getBytes().length >= s2.getBytes().length ) return s1;
else return s2;}
));
// BinaryOperator<String> 사용
String str = Arrays.stream(greetings).reduce(new CompareString()).get();
System.out.println(str);
}
}
public class TravelCustomer {
private String name; //이름
private int age; //나이
private int price; //가격
public TravelCustomer(String name, int age, int price) {
this.name = name;
this.age = age;
this.price = price;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getPrice() {
return price;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public void setPrice(int price) {
this.price = price;
}
public String toString() {
return "name: " + name + " age: " + age + " price: " + price;
}
}
public class TravelTest {
public static void main(String[] args) {
TravelCustomer mari = new TravelCustomer("마리", 19, 100);
TravelCustomer rico = new TravelCustomer("리코", 18, 100);
TravelCustomer yoshiko = new TravelCustomer("요시코", 17, 50);
List<TravelCustomer> cList = new ArrayList<TravelCustomer>();
cList.add(mari);
cList.add(rico);
cList.add(yoshiko);
System.out.println("고객 명단을 추가된 순서대로 출력");
// 이름(getName)만 가져와서(map) 출력
cList.stream().map(c->c.getName()).forEach(s -> System.out.println(s));
System.out.println("총 여행 비용");
// mapToInt()로 비용(getPrice)를 int화 한 후 sum 한 것을 출력
System.out.println(cList.stream().mapToInt(c->c.getPrice()).sum());
System.out.println("18세 이상 고객 명단을 정렬하여 출력");
// 나이(getAge) 가 18 이상인 요소를 필터링(filter)한 후 이름(getName)을 가져온 뒤 정렬(sorted) 하여 출력
cList.stream().filter(c->c.getAge() >= 18).map(c->c.getName()).sorted().forEach(s-> System.out.println(s));
}
}