[TIL] 231019 List removeIf()

CountryGirlยท2023๋…„ 10์›” 19์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
80/80

๋ฌธ์ œ๋ฅผ ํ’€๋‹ค๊ฐ€ ์•„์ฃผ ์ข‹์€ ๋ฉ”์„œ๋“œ๋ฅผ ๋ฐœ๊ฒฌํ•˜๊ฒŒ ๋˜์—ˆ๋‹ค(?)

String myString = "dxccxbbbxxaaaa";
List<String> xSplit = new ArrayList<>(Arrays.asList(myString.split("x")));
stringArray = [d, cc, bbb, , aaaa]

x๋กœ split() ์„ ํ•˜๊ฒŒ ๋˜๋ฉด "" ์ด ๋“ค์–ด๊ฐ„๋‹ค. ๊ณต๋ฐฑ์„ ์—†์• ์ฃผ๊ธฐ ์œ„ํ•ด์„œ
์•„๋ž˜์™€ ๊ฐ™์ด ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ–ˆ๋‹ค.

for (String s : strings.) {
	if (s.length() == 0) strings.remove(s);
}

ํ•˜์ง€๋งŒ intelliJ ์—์„œ ๋…ธ๋ž€์ค„์ด ๊ทธ์–ด์ง€๋ฉด์„œ ์ถ”์ฒœํ•ด์ค€ ์ฝ”๋“œ๊ฐ€ ์žˆ์—ˆ๋‹ค!

๐Ÿ’ก ๊ทธ๊ฒƒ์€ ๋ฐ”๋กœ!

๐Ÿ’ก removeIf()

List<String> xSplit = new ArrayList<>(Arrays.asList(myString.split("x")));
xSplit.removeIf(s -> s.length() == 0);
  • Java 8๋ถ€ํ„ฐ ์ถ”๊ฐ€๋œ List ์ธํ„ฐํŽ˜์ด์Šค์˜ ๊ธฐ๋ณธ ๋ฉ”์„œ๋“œ ์ค‘ ํ•˜๋‚˜
  • ์ฃผ์–ด์ง„ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๋Š” ์š”์†Œ๋ฅผ ์ œ๊ฑฐํ•˜๋Š”๋ฐ ์‚ฌ์šฉ

๋‚˜๋Š” ์ด ์ฝ”๋“œ์—์„œ ์ฃผ์–ด์ง„ ์กฐ๊ฑด์œผ๋กœ ๋žŒ๋‹ค ํ‘œํ˜„์‹ s -> s.length() == 0๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค!

(s -> s.length() == 0) : ์ด ๋žŒ๋‹ค ํ‘œํ˜„์‹์€ ๊ธธ์ด๊ฐ€ 0์ธ ๋ฌธ์ž์—ด์„ ์กฐ๊ฑด์œผ๋กœ ์„ค์ •ํ•ด ๊ธธ์ด๊ฐ€ 0์ธ ๋ฌธ์ž์—ด์„ ์ œ๊ฑฐํ•œ๋‹ค!

profile
๐Ÿ’ป๐ŸŒพ์‹œ๊ณจ์†Œ๋…€์˜ ์—‰๋ง์ง•์ฐฝ ๊ฐœ๋ฐœ ์„ฑ์žฅ์ผ์ง€๐ŸŒพ๐Ÿ’ป (2023.05.23 ~)

0๊ฐœ์˜ ๋Œ“๊ธ€