Java Collections Framework: List, Set, Map

๐Ÿ’ก Java Collections Framework: List, Set, Map โ€” Executive Summary

Technical architectural analysis, practical configuration manifests, and deployment instructions for Java Collections Framework: List, Set, Map.

Subpage

Spring


Roadmap

Java Collection

Map
Object โ†’ Map (Jackson.ObjectMapper)
java
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person(12, "kim");
Map<String, Object> map = objectMapper.convertValue(person, Map.class);
Map โ†’ String for Logging (Collection.Stream)
java
String resultSet =
        {{ map_var }}.entrySet()
                .stream()
                .map(e -> e.getKey() + "=" + String.join(", ", e.getValue()))
                .collect(Collectors.joining(" "));
log.debug(resultSet);
...
List
Array Parse with List (Lists or Arrays)
java
// List to Array
long[] longArr = Longs.toArray(longList);

// List to Array (Object)
String[] strArr = StringList.toArray(new String[0]);

// Array to List
Integer[] sourceArray = { 0, 1, 2, 3, 4, 5 };
List<Integer> targetList = Lists.newArrayList(sourceArray);
List<String> targetList2 = Arrays.asList(new String[] {""});
JSON
Object โ†’ JsonString (Jackson.ObjectMapper)

The Object -> Json conversion process is called serialization. In addition to String, Jackson can also write to files or streams.

java
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person("Nicole", 20);

String personJson = objectMapper.writeValueAsString(person);

System.out.println(personJson);
JsonString โ†’ Object (Jackson.ObjectMapper)

The Json -> Object conversion process is called Deserialization. Like serialization, it is also possible to write to a file or stream.

java
String personJson = "{isJsonString}"
Person jsonToPerson = objectMapper.readValue(personJson, Person.class);
Reactive Streams
Comparison items Java Stream API WebFlux (Project Reactor)
How it works Pull-based (synchronous) Push-based (asynchronous)
Blocking Blocking. The thread waits until all data has been collected. Non-blocking. Schedule to be notified when the data is ready.
Data Source Collections already in memory (List, Set, etc.) Data flow that does not know when it will arrive (network, DB, etc.)
Purpose of use Quickly calculate large amounts of data (parallel processing, etc.) Efficiently handle many concurrent requests with fewer threads
Reusability Consume it once and it’s over (closed) Multiple subscription possible
Java Stream
java
/* Stream.map() */
List<?> baseList = new ArrayList<>();
List<?> rtnList = baseList.stream().map(obj->{
	return obj.value
}).collect(Collectors.toList());

/** Map ๋‚ด ๋ชจ๋“  ๋ฆฌ์ŠคํŠธ ๋ณ‘ํ•ฉ */
((HashMap<String,List<String>>) obj).values().stream().flatMap(List::stream).collect(Collectors.toList()));

/** ํ‘œํ˜„์‹ ์„ค๋ช… ์•„๋ž˜ ๋ชจ๋‘ ๊ธฐ๋Šฅ ๋™์ผ*/
// .A(B::C) ์ข…๋ฅ˜ (.A(D->{})๋ฅผ ๊ฐ€์ •)
// 1. .A(D->D.C())
.map(Map.Entry::getValue) == .map(entry -> entry.getValue())
// 2. Consumer<T(D)> void : .A(D->B.C(D))
.forEach(System.out::println) == .forEach(item -> System.out.println(item))
// 3. Supplier<T(new)> retrun T : .A(()->B.C())
(Math::random) == (()->Math.random())
// 4. Function<T(D),T(B)> ? : .A(D->B.C(D))
(Interger::parseInt) == (str->Integer.parseInt(str));
// 5. Predicate<T(B)> return Boolean : .A(D->D.C())
(String::isEmpty)
// ์ด๊ฒƒ์„ ๋‹จ์ˆœํ™”ํ•˜๋ ค ํ•ด๋ณด์•˜์ง€๋งŒ, ๋ถ„์„๊ฒฐ๊ณผ ์‚ฌ์‹ค Functional Interface์˜ ์ •์˜์— ๋”ฐ๋ผ ๋ชจ๋‘ ๋‹ค๋ฅธ ๊ฒฐ๊ณผ์ผ๊ฒƒ์œผ๋กœ ๋ณด์ž„
WebFlux (Project Reactor)
java
//ClientRequest

//ClientResponse
response.bodyToMono()

//Body and Mono
Publisher.subscribe(
	value -> { //when then (Published value)
	},
	error -> { //when throwed
	},
	() -> { //when completed
	}
)
Failed
java
//ClientResponse๋ฅผ Publisher(bodyToMono(), bodyToFlux())๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ๋กœ๊น…
//์™ธ๋ถ€ ์›นํด๋ผ์ด์–ธํŠธ์˜ ์ด๋ฒคํŠธ์— ์˜ํ•ด ๋‹ค์ค‘์‹คํ–‰๋˜๋Š” ๋ฉ”์„œ๋“œ์ด๋ฏ€๋กœ subscribe()-๋น„๋™๊ธฐ-๋ฅผ ํ•˜๊ฒŒ๋˜๋ฉด ์—๋Ÿฌ๋ฐœ์ƒ.

/** ์—๋Ÿฌ ์˜ˆ์‹œ */
            clientResponse.bodyToMono(String.class)
                    .doOnNext(responseBody -> {
                        sb.append("\tBody: \n");
                        sb.append("\t\tContents: " + responseBody + " \n");
                    })
                    .doOnTerminate(()-> {
                        log.info(sb.toString());
                    })
                    .subscribe();
            return Mono.just(clientResponse);

/** ์ž˜๋ชป๋œ ์˜ˆ์‹œ */
            clientResponse.bodyToMono(String.class)
                    .flatMap(responseBody -> {
                        sb.append("\tBody: \n");
                        sb.append("\t\tContents: " + responseBody + " \n");
                        log.info(sb.toString());
                        return Mono.empty();
                    });
            return Mono.just(clientResponse);
/*
java.lang.IllegalStateException: block()/blockFirst()/blockLast() are blocking, which is not supported in thread reactor-http-nio-2
์ด ๋ฉ”์‹œ์ง€๋Š” ๋‹ค์Œ์„ ๋‚˜ํƒ€๋ƒ…๋‹ˆ๋‹ค:

block(), blockFirst(), ๋˜๋Š” blockLast()์™€ ๊ฐ™์€ ๋ธ”๋กœํ‚น ์—ฐ์‚ฐ์„ ์Šค๋ ˆ๋“œ "reactor-http-nio-2"์—์„œ ์‚ฌ์šฉํ•˜๊ณ  ์žˆ๋‹ค๋Š” ๊ฒƒ์ž…๋‹ˆ๋‹ค.
Reactor๋Š” ๋น„๋™๊ธฐ ๋ฐ ๋…ผ๋ธ”๋กœํ‚น ์ŠคํŠธ๋ฆผ ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•ด ์„ค๊ณ„๋˜์—ˆ์œผ๋ฏ€๋กœ ๋ธ”๋กœํ‚น ์—ฐ์‚ฐ์„ ์‚ฌ์šฉํ•˜๋ฉด ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
*/

/** ๋ฐฉ๋ฒ• */
            clientResponse.bodyToMono(String.class)
                    .subscribeOn(Schedulers.elastic())
                    .subscribe(responseBody -> {
                        sb.append("\tBody: \n");
                        sb.append("\t\tCount: " + JsonParserFactory.getJsonParser().parseMap(responseBody).size() + " \n");
                        sb.append("\t\tContents: " + responseBody + " \n");
                        log.info(sb.toString());
                    });
//            }
            return Mono.just(clientResponse);

/* Steam์„ ์ฆ‰์‹œ ์ข…๋ฃŒํ•˜๊ณ  ๋‚ด์šฉ๋ฌผ์„ ๊บผ๋‚ด๊ธฐ */
Mono<String> mono = Mono.just("Hello, Reactor!");

mono
    .take(1)
    .subscribe(
        value -> {
            // ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋ฅผ ์ฒ˜๋ฆฌํ•ฉ๋‹ˆ๋‹ค.
            System.out.println("Received value: " + value);
        },
        error -> {
            // ์—๋Ÿฌ ์ฒ˜๋ฆฌ
        },
        () -> {
            // ์™„๋ฃŒ ์ฒ˜๋ฆฌ
        }
    );
Method Input Output Reactor processing (Unwrapping)
map T R (generic object) Move on to the next step as received
flatMap T Mono or Flux Open the box Take out only the contents R and move on to the next step
flatMapMany T Flux Expands Mono into Flux, which contains multiple particles.
flatMapIterable T Iterable (List, etc.) The list is split one by one and exported sequentially.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *