๊ด€๋ฆฌ ๋ฉ”๋‰ด

Unfazedโ—๏ธ๐ŸŽฏ

์ปฌ๋ ‰์…˜ ํ”„๋ ˆ์ž„์›๊ณผ ํ•จ์ˆ˜ํ˜• ์ธํ„ฐํŽ˜์ด์Šค ๋ณธ๋ฌธ

Java

์ปฌ๋ ‰์…˜ ํ”„๋ ˆ์ž„์›๊ณผ ํ•จ์ˆ˜ํ˜• ์ธํ„ฐํŽ˜์ด์Šค

9taetae9 2023. 10. 6. 21:46
728x90

ํ•จ์ˆ˜ํ˜• ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ปฌ๋ ‰์…˜ ํ”„๋ ˆ์ž„์›์˜ ๋ฉ”์„œ๋“œ

์ธํ„ฐํŽ˜์ด์Šค ๋ฉ”์„œ๋“œ ์„ค๋ช…
Collection boolean removelf(Predicate<E> filter) ์กฐ๊ฑด์— ๋งž๋Š” ์š”์†Œ๋ฅผ ์‚ญ์ œ
List void replaceAll(UnaryOperator<E> operator) ๋ชจ๋“  ์š”์†Œ๋ฅผ ๋ณ€ํ™˜ํ•˜์—ฌ ๋Œ€์ฒด
Iterable void forEach(Consumer<T> action) ๋ชจ๋“  ์š”์†Œ์— ์ž‘์—… action์„ ์ˆ˜ํ–‰
Map V compute(K key, BiFunction<K,V,V> f) ์ง€์ •๋œ ํ‚ค์˜ ๊ฐ’์— ์ž‘์—… f๋ฅผ ์ˆ˜ํ–‰
V computeIfAbsent(K key, Function<K,V> f) ํ‚ค๊ฐ€ ์—†์œผ๋ฉด, ์ž‘์—… f ์ˆ˜ํ–‰ ํ›„ ์ถ”๊ฐ€
V computeIfPresent(K key, Bifunction<K,V,V> f) ์ง€์ •๋œ ํ‚ค๊ฐ€ ์žˆ์„ ๋•Œ ์ž‘์—… f ์ˆ˜ํ–‰
V merge(K key, V value, BiFunction<V,V,V> f) ๋ชจ๋“  ์š”์†Œ์— ๋ณ‘ํ•ฉ์ž‘์—… f ์ˆ˜ํ–‰
void forEach(BiConsumer<K,V> action) ๋ชจ๋“  ์š”์†Œ์— ์ž‘์—… action์„ ์ˆ˜ํ–‰
void replaceAll(Bifunction<K,V,V> f) ๋ชจ๋“  ์š”์†Œ์— ์น˜ํ™˜์ž‘์—… f๋ฅผ ์ˆ˜ํ–‰

list.forEach(i->System.outprint(i+", ")); //list์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ ์ถœ๋ ฅ

list.removeIf(x->x%2==0 || x%3 == 0); //2 ๋˜๋Š” 3์˜ ๋ฐฐ์ˆ˜ ์ œ๊ฑฐ

list.replaceAll(i->i*10);  // ๋ชจ๋“  ์š”์†Œ์— 10 ๊ณฑํ•œ๋‹ค.

map.forEach((k,v)-> System.out.print("{"+k+", "+v+"} ,"));  //map์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ {k, v}์˜ ํ˜•์‹์œผ๋กœ ์ถœ๋ ฅ

์ฃผ์š” ์ธํ„ฐํŽ˜์ด์Šค ๊ฐ„์˜ ์ƒ์† ๊ด€๊ณ„

public static void main(String[] args) {

ArrayList<Integer> list = new ArrayList<>();

for(int i=0; i<10; i++)

list.add(i);

 

//list์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ ์ถœ๋ ฅ

list.forEach(i->System.out.print(i+", "));

System.out.println();

 

//list์—์„œ 2๋˜๋Š” 3 ๋ฐฐ์ˆ˜ ์ œ๊ฑฐ

list.removeIf(x->x%2==0 || x%3 ==0);

System.out.println(list);

 

list.replaceAll(i->i*10); //list์˜ ๊ฐ์š”์†Œ์— 10์„ ๊ณฑํ•œ๋‹ค.

System.out.println(list);

 

Map<String, String> map = new HashMap<>();

map.put("1","1");

map.put("2","2");

map.put("3","3");

map.put("4","4");

 

//map์˜ ๋ชจ๋“  ์š”์†Œ๋ฅผ {k, v}์˜ ํ˜•์‹์œผ๋กœ ์ถœ๋ ฅํ•œ๋‹ค.

map.forEach((k,v)->System.out.println("{"+k+","+v+"},"));

System.out.println();

 

Iterator it = map.entrySet().iterator();

while(it.hasNext()) {

System.out.println(it.next());

}

 

}

 

output:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9,

[1, 5, 7]

[10, 50, 70]

{1,1},

{2,2},

{3,3},

{4,4},

 

1=1

2=2

3=3

4=4

728x90