Skip to content

Instantly share code, notes, and snippets.

@namkyu
Last active November 7, 2018 06:13
Show Gist options
  • Save namkyu/940744d9233566918790b0b22d8cd7e4 to your computer and use it in GitHub Desktop.
Save namkyu/940744d9233566918790b0b22d8cd7e4 to your computer and use it in GitHub Desktop.
lambda #java8

람다식

(int n, String str) -> { return str + n; }
(int n, String str) -> str + n
(n, str) -> str + n
str -> str + 1
() -> "Hello, World!"
() -> {}

foreach

map.get(N).forEach(element -> {
    String title = element.select("dt > a").attr("title");   
});

==========================================================================

items.forEach((k,v) -> System.out.println("Item : " + k + " Count : " + v));

filter()

특정 조건과 일치하는 모든 요소를 담은 새로운 스트림을 반환

List<String> words = Arrays.asList("a", "b", "c");

List<String> result = words.stream()
    .filter(word -> "b".equals(word) == false)
    .collect(Collectors.toList());

result.forEach(System.out::println);

==========================================================================

List<PersonTest> persons = Arrays.asList(
    new PersonTest("nklee", 37),
    new PersonTest("dy", 36),
    new PersonTest("wife", 37)
);

PersonTest personTest = persons.stream() // Convert to stream
        .filter(person -> "nklee".equals(person.getName())) // we want to get nklee object
        .findAny() // return found object
        .orElse(null); // If not found, return null

System.out.println(personTest);

Stream

Map<String, String> map = new HashMap<>();
	map.put("1", "1");
	map.put("2", "2");
	map.put("3", "3");

	map.entrySet()
	        .stream()
	        .limit(2)
	        .forEach(System.out::println);

==========================================================================

String[] arr = new String[]{"1", "2", "3"};
Stream.of(arr).limit(2).forEach(System.out::println);

Stream map()

스트림에 있는 값들을 특정 방식으로 변환하여 새로운 스트림을 반환

List<String> collect = Stream.of(ContentType.values())
	.filter(contentType -> contentType.isVisible())
	.map(ContentType::getDescription)
	.collect(Collectors.toList());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment