Java Lambda: Difference between revisions

From Chorke Wiki
Jump to navigation Jump to search
No edit summary
Line 1: Line 1:
<source lang="java">
<syntaxhighlight lang="java">
Map<String, String> insured = Stream.of("Adults:1", "Children:1", "Senior Citizen:10")
Map<String, String> insured = Stream.of("Adults:1", "Children:1", "Senior Citizen:10")
                                     .map(pair -> pair.split(":"))
                                     .map(pair -> pair.split(":"))
                                     .collect(Collectors.toMap(pair -> pair[0], pair->pair[1]));
                                     .collect(Collectors.toMap(pair -> pair[0], pair->pair[1]));
</source>
</syntaxhighlight>


<source lang="java">
<syntaxhighlight lang="java">
Double totalInsured = insured.values().stream().mapToDouble(d -> Double.parseDouble(d)).sum();
Double totalInsured = insured.values().stream().mapToDouble(d -> Double.parseDouble(d)).sum();
Double totalInsured = insured.values().stream().mapToDouble(Double::parseDouble).sum();
Double totalInsured = insured.values().stream().mapToDouble(Double::parseDouble).sum();
</source>
</syntaxhighlight>


<source lang="java">
<syntaxhighlight lang="java">
Integer totalInsured = insured.values().stream().mapToInt(d -> Integer.parseInt(d)).sum();
Integer totalInsured = insured.values().stream().mapToInt(d -> Integer.parseInt(d)).sum();
Integer totalInsured = insured.values().stream().mapToInt(Integer::parseInt).sum();
Integer totalInsured = insured.values().stream().mapToInt(Integer::parseInt).sum();
</source>
</syntaxhighlight>


<source lang="java">
<syntaxhighlight lang="java">
Map<String, String> filter  = insured.entrySet().stream()
Map<String, String> filter  = insured.entrySet().stream()
                                     .filter(map -> !"Children".equals(map.getKey()))
                                     .filter(map -> !"Children".equals(map.getKey()))
Line 21: Line 21:


Integer totalInsured = filter.values().stream().mapToInt(Integer::parseInt).sum();
Integer totalInsured = filter.values().stream().mapToInt(Integer::parseInt).sum();
</source>
</syntaxhighlight>
----
----
<source lang="java">
<syntaxhighlight lang="java">
Map<String, String> mapping =  Stream.of("travel_adult:Adults", "travel_children:Children", "travel_senior_citizen:Senior Citizen")
Map<String, String> mapping =  Stream.of("travel_adult:Adults", "travel_children:Children", "travel_senior_citizen:Senior Citizen")
                                     .map(pair -> pair.split(":"))
                                     .map(pair -> pair.split(":"))
Line 30: Line 30:
Map<String, String> reverse = mapping.entrySet().stream()
Map<String, String> reverse = mapping.entrySet().stream()
                                     .collect(Collectors.toMap(map -> map.getValue(), map -> map.getKey()));
                                     .collect(Collectors.toMap(map -> map.getValue(), map -> map.getKey()));
</source>
</syntaxhighlight>
----
----
<source lang="java">
<syntaxhighlight lang="java">
int totalInsured = properties.entrySet().stream()
int totalInsured = properties.entrySet().stream()
         .filter(map-> ArrayUtils.contains(INSURED_OBJECT_MAP.values().toArray(), map.getKey()))
         .filter(map-> ArrayUtils.contains(INSURED_OBJECT_MAP.values().toArray(), map.getKey()))
         .collect(Collectors.toMap(map -> map.getKey(), map -> (Integer)map.getValue()))
         .collect(Collectors.toMap(map -> map.getKey(), map -> (Integer)map.getValue()))
         .values().stream().mapToInt(Integer::new).sum();
         .values().stream().mapToInt(Integer::new).sum();
</source>
</syntaxhighlight>


----
----
<source lang="java">
<syntaxhighlight lang="java">
private static Map<String, Object> decode(String encode) {
private static Map<String, Object> decode(String encode) {
     return Stream.of(encode.split(LIST_SPLITTER))
     return Stream.of(encode.split(LIST_SPLITTER))
Line 47: Line 47:
             .collect(Collectors.toMap(array -> array[0], array -> array[1]));
             .collect(Collectors.toMap(array -> array[0], array -> array[1]));
}
}
</source>
</syntaxhighlight>


==Collectors==
==Collectors==
<source lang="Java">
<syntaxhighlight lang="Java">
import java.util.Map;
import java.util.Map;
import java.util.List;
import java.util.List;
Line 57: Line 57:
import java.util.Collections;
import java.util.Collections;
import java.util.stream.Collectors;
import java.util.stream.Collectors;
</source>
</syntaxhighlight>


===Collectors » Example 1===
===Collectors » Example 1===
<source lang="Java">
<syntaxhighlight lang="Java">
List<Map> list = new ArrayList<>();
List<Map> list = new ArrayList<>();
Map<String, Object> commission1 = new HashMap<>();
Map<String, Object> commission1 = new HashMap<>();
Line 92: Line 92:
System.out.println(filteredList.stream().map(m->String.valueOf(m.get("Total"))).collect(Collectors.toList()));
System.out.println(filteredList.stream().map(m->String.valueOf(m.get("Total"))).collect(Collectors.toList()));
System.out.println(filteredList.stream().map(m->String.valueOf(m.get("Total"))).collect(Collectors.joining(",")));
System.out.println(filteredList.stream().map(m->String.valueOf(m.get("Total"))).collect(Collectors.joining(",")));
</source>
</syntaxhighlight>


===Collectors » Example 2===
===Collectors » Example 2===
<source lang="Java">
<syntaxhighlight lang="Java">
Map<String, String> requestHeaders = new HashMap<>();
Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("X-Auth-Token", "JWT");
requestHeaders.put("X-Auth-Token", "JWT");
Line 109: Line 109:
     .stream().filter(e -> mapper.containsKey(e.getKey()))
     .stream().filter(e -> mapper.containsKey(e.getKey()))
     .collect(Collectors.toMap(e -> mapper.get(e.getKey()), e -> e.getValue()));
     .collect(Collectors.toMap(e -> mapper.get(e.getKey()), e -> e.getValue()));
</source>
</syntaxhighlight>


===Collectors » Example 3===
===Collectors » Example 3===
<source lang="Java">
<syntaxhighlight lang="Java">
String[] paths = new String[]{
String[] paths = new String[]{
     "/home/chorke/sites/staging/certificates/chorke-00-000.pdf",
     "/home/chorke/sites/staging/certificates/chorke-00-000.pdf",
Line 124: Line 124:
     return path.replace(pathPrefix, "");
     return path.replace(pathPrefix, "");
}).collect(Collectors.toList());
}).collect(Collectors.toList());
</source>
</syntaxhighlight>


==Deserialize==
==Deserialize==
<source lang="Java">
<syntaxhighlight lang="Java">
import java.util.Map;
import java.util.Map;
import java.util.List;
import java.util.List;
Line 135: Line 135:
import java.util.stream.Stream;
import java.util.stream.Stream;
import java.util.stream.Collectors;
import java.util.stream.Collectors;
</source>
</syntaxhighlight>


===Example » Seed Data===
===Example » Seed Data===
<source lang="Java">
<syntaxhighlight lang="Java">
Stream<String> lines = Stream.of(
Stream<String> lines = Stream.of(
     "name:Anika,slug:hamida-anika,status:permitted",
     "name:Anika,slug:hamida-anika,status:permitted",
Line 148: Line 148:


String workflows = "id:1000001,slug:motor-bike-insurance;id:1000002,slug:motor-car-insurance;id:1000003,slug:travel-insurance";
String workflows = "id:1000001,slug:motor-bike-insurance;id:1000002,slug:motor-car-insurance;id:1000003,slug:travel-insurance";
</source>
</syntaxhighlight>


===Example » Deserialize===
===Example » Deserialize===
<source lang="Java">
<syntaxhighlight lang="Java">
List<Map<String, String>> nephews = new ArrayList<>();
List<Map<String, String>> nephews = new ArrayList<>();
//var nephews = new ArrayList<Map<String, String>>();
//var nephews = new ArrayList<Map<String, String>>();
Line 161: Line 161:


System.out.println(String.format("%s", nephews));
System.out.println(String.format("%s", nephews));
</source>
</syntaxhighlight>


<source lang="Java">
<syntaxhighlight lang="Java">
// [id:1000001, slug:motor-bike-insurance], [id:1000002, slug:motor-car-insurance], [id:1000003, slug:travel-insurance]]
// [id:1000001, slug:motor-bike-insurance], [id:1000002, slug:motor-car-insurance], [id:1000003, slug:travel-insurance]]
Object products = Stream.of(workflows.split(";")).map(
Object products = Stream.of(workflows.split(";")).map(
Line 174: Line 174:
     .collect(Collectors.toMap(pair -> pair[0], pair->pair[1]))
     .collect(Collectors.toMap(pair -> pair[0], pair->pair[1]))
).collect(Collectors.toList());
).collect(Collectors.toList());
</source>
</syntaxhighlight>


<source lang="Java">
<syntaxhighlight lang="Java">
// Optional[{id=1000001, slug=motor-bike-insurance}]
// Optional[{id=1000001, slug=motor-bike-insurance}]
Object products = Stream.of(workflows.split(";")).map(
Object products = Stream.of(workflows.split(";")).map(
Line 192: Line 192:
.parallel().filter(map -> "motor-bike-insurance".equals(map.get("slug")))
.parallel().filter(map -> "motor-bike-insurance".equals(map.get("slug")))
.map(map -> map.get("id")).findFirst();
.map(map -> map.get("id")).findFirst();
</source>
</syntaxhighlight>


<source lang="Java">
<syntaxhighlight lang="Java">
// 1000001
// 1000001
Object products = Stream.of(workflows.split(";")).map(
Object products = Stream.of(workflows.split(";")).map(
Line 212: Line 212:


System.out.println(String.format("%s", products));
System.out.println(String.format("%s", products));
</source>
</syntaxhighlight>


===Example » Predication===
===Example » Predication===
<source lang="Java">
<syntaxhighlight lang="Java">
boolean anyMatch  = nephews.stream().anyMatch( nephew -> "Anika".equals(nephew.get("name")));
boolean anyMatch  = nephews.stream().anyMatch( nephew -> "Anika".equals(nephew.get("name")));
boolean noneMatch = nephews.stream().noneMatch(nephew -> "Raida".equals(nephew.get("name")));
boolean noneMatch = nephews.stream().noneMatch(nephew -> "Raida".equals(nephew.get("name")));
boolean allMatch  = nephews.stream().allMatch( nephew -> nephew.get("name").startsWith("A"));
boolean allMatch  = nephews.stream().allMatch( nephew -> nephew.get("name").startsWith("A"));
</source>
</syntaxhighlight>


===Example » Filter===
===Example » Filter===
<source lang="Java">
<syntaxhighlight lang="Java">
List<Map<String, String>> filter = nephews.stream().filter(nephew -> nephew.get("name").startsWith("A")).collect(Collectors.toList());
List<Map<String, String>> filter = nephews.stream().filter(nephew -> nephew.get("name").startsWith("A")).collect(Collectors.toList());


List<String> names = nephews.stream().map(nephew -> nephew.get("name")).collect(Collectors.toCollection(ArrayList::new));
List<String> names = nephews.stream().map(nephew -> nephew.get("name")).collect(Collectors.toCollection(ArrayList::new));
List<String> names = nephews.stream().map(nephew -> nephew.get("name")).collect(Collectors.toList());
List<String> names = nephews.stream().map(nephew -> nephew.get("name")).collect(Collectors.toList());
</source>
</syntaxhighlight>


===Example » Sorted===
===Example » Sorted===
<source lang="Java">
<syntaxhighlight lang="Java">
names.stream().forEach(System.out::println);
names.stream().forEach(System.out::println);
names.stream().forEachOrdered(System.out::println);
names.stream().forEachOrdered(System.out::println);
names.stream().sorted().forEach(System.out::println);
names.stream().sorted().forEach(System.out::println);
names.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
names.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
</source>
</syntaxhighlight>


==References==
==References==

Revision as of 20:25, 24 October 2024

Map<String, String> insured = Stream.of("Adults:1", "Children:1", "Senior Citizen:10")
                                    .map(pair -> pair.split(":"))
                                    .collect(Collectors.toMap(pair -> pair[0], pair->pair[1]));
Double totalInsured = insured.values().stream().mapToDouble(d -> Double.parseDouble(d)).sum();
Double totalInsured = insured.values().stream().mapToDouble(Double::parseDouble).sum();
Integer totalInsured = insured.values().stream().mapToInt(d -> Integer.parseInt(d)).sum();
Integer totalInsured = insured.values().stream().mapToInt(Integer::parseInt).sum();
Map<String, String> filter  = insured.entrySet().stream()
                                     .filter(map -> !"Children".equals(map.getKey()))
                                     .collect(Collectors.toMap(map -> map.getKey(), map -> map.getValue()));

Integer totalInsured = filter.values().stream().mapToInt(Integer::parseInt).sum();

Map<String, String> mapping =  Stream.of("travel_adult:Adults", "travel_children:Children", "travel_senior_citizen:Senior Citizen")
                                     .map(pair -> pair.split(":"))
                                     .collect(Collectors.toMap(pair -> pair[0], pair->pair[1]));

Map<String, String> reverse = mapping.entrySet().stream()
                                     .collect(Collectors.toMap(map -> map.getValue(), map -> map.getKey()));

int totalInsured = properties.entrySet().stream()
        .filter(map-> ArrayUtils.contains(INSURED_OBJECT_MAP.values().toArray(), map.getKey()))
        .collect(Collectors.toMap(map -> map.getKey(), map -> (Integer)map.getValue()))
        .values().stream().mapToInt(Integer::new).sum();

private static Map<String, Object> decode(String encode) {
    return Stream.of(encode.split(LIST_SPLITTER))
            .map(String::trim).collect(Collectors.toList())
            .stream().map(pair -> pair.split(PAIR_SPLITTER))
            .collect(Collectors.toMap(array -> array[0], array -> array[1]));
}

Collectors

import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.Collectors;

Collectors » Example 1

List<Map> list = new ArrayList<>();
Map<String, Object> commission1 = new HashMap<>();
commission1.put("Total", 1000);
commission1.put("rate", 10);
list.add(commission1);

Map<String, Object> commission2 = new HashMap<>();
commission2.put("Total", 10000);
commission2.put("rate", 10);
list.add(commission2);

Map<String, Object> commission3 = new HashMap<>();
commission3.put("Tutal", 10000);
commission3.put("rate", 10);
list.add(commission3);

//list.stream().filter(m-> m.containsKey("Total")).collect(Collectors.toList());
System.out.println(list.stream().filter(m-> m.containsKey("Total")).collect(Collectors.toList()));
list.stream().filter(m-> m.containsKey("Total")).collect(Collectors.toList()).forEach(m -> System.out.println(m.get("Total")));

//list.stream().filter(m-> m.containsKey("Total")).mapToInt(m -> (int)m.get("Total")).sum()
System.out.println(list.stream().filter(m-> m.containsKey("Total")).mapToInt(m -> (int)m.get("Total")).sum());

//list.stream().filter(m-> m.containsKey("Total")).map(m->m.get("Total")).collect(Collectors.toList())
System.out.println(list.stream().filter(m-> m.containsKey("Total")).map(m->m.get("Total")).collect(Collectors.toList()));

List<Map> filteredList = list.stream().filter(m-> m.containsKey("Total")).collect(Collectors.toList());
System.out.println(filteredList.stream().map(m->m.get("Total")).collect(Collectors.toList()));

System.out.println(filteredList.stream().map(m->String.valueOf(m.get("Total"))).collect(Collectors.toList()));
System.out.println(filteredList.stream().map(m->String.valueOf(m.get("Total"))).collect(Collectors.joining(",")));

Collectors » Example 2

Map<String, String> requestHeaders = new HashMap<>();
requestHeaders.put("X-Auth-Token", "JWT");
requestHeaders.put("Content-Type", "Application/Json");
requestHeaders.put("Accept", "Application/Json");

Map<String, String> mapper = new HashMap<>();
mapper.put("X-Auth-Token", "Authorization");
mapper.put("Content-Type", "Content-Type");
mapper.put("Accept", "Accept");

Map<String, String> headers = requestHeaders.entrySet()
    .stream().filter(e -> mapper.containsKey(e.getKey()))
    .collect(Collectors.toMap(e -> mapper.get(e.getKey()), e -> e.getValue()));

Collectors » Example 3

String[] paths = new String[]{
    "/home/chorke/sites/staging/certificates/chorke-00-000.pdf",
    "/home/chorke/sites/staging/certificates/chorke-00-001.pdf",
    "/home/chorke/sites/staging/certificates/chorke-00-002.pdf",
};

List<String> suffixes = Arrays.stream(paths).map(path -> {
    String pathPrefix = "/home/chorke/sites/staging";
    if (!pathPrefix.endsWith("/")) pathPrefix = String.format("%s/", pathPrefix);
    return path.replace(pathPrefix, "");
}).collect(Collectors.toList());

Deserialize

import java.util.Map;
import java.util.List;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.stream.Stream;
import java.util.stream.Collectors;

Example » Seed Data

Stream<String> lines = Stream.of(
    "name:Anika,slug:hamida-anika,status:permitted",
    "name:Khaled,slug:galib-khaled,status:permitted",
    "name:Mannat,slug:halima-mannat,status:permitted",
    "name:Raiyan,slug:shahed-raiyan,status:permitted",
    "name:Aursha,slug:al-raji-aursha,status:permitted"
);

String workflows = "id:1000001,slug:motor-bike-insurance;id:1000002,slug:motor-car-insurance;id:1000003,slug:travel-insurance";

Example » Deserialize

List<Map<String, String>> nephews = new ArrayList<>();
//var nephews = new ArrayList<Map<String, String>>();

lines.forEach(line -> nephews.add(
    Stream.of(line.split(",")).map(pair -> pair.split(":"))
    .collect(Collectors.toMap(pair -> pair[0], pair->pair[1]))
));

System.out.println(String.format("%s", nephews));
// [id:1000001, slug:motor-bike-insurance], [id:1000002, slug:motor-car-insurance], [id:1000003, slug:travel-insurance]]
Object products = Stream.of(workflows.split(";")).map(
    workflow -> Stream.of(workflow.split(",")).collect(Collectors.toList())
).collect(Collectors.toList());

// [{id=1000001, slug=motor-bike-insurance}, {id=1000002, slug=motor-car-insurance}, {id=1000003, slug=travel-insurance}]
Object products = Stream.of(workflows.split(";")).map(
    workflow -> Stream.of(workflow.split(",")).map(pair -> pair.split(":"))
    .collect(Collectors.toMap(pair -> pair[0], pair->pair[1]))
).collect(Collectors.toList());
// Optional[{id=1000001, slug=motor-bike-insurance}]
Object products = Stream.of(workflows.split(";")).map(
    workflow -> Stream.of(workflow.split(",")).map(pair -> pair.split(":"))
    .collect(Collectors.toMap(pair -> pair[0], pair->pair[1]))
)
.parallel().filter(map -> "motor-bike-insurance".equals(map.get("slug")))
.findFirst();

// Optional[1000001]
Object products = Stream.of(workflows.split(";")).map(
    workflow -> Stream.of(workflow.split(",")).map(pair -> pair.split(":"))
    .collect(Collectors.toMap(pair -> pair[0], pair->pair[1]))
)
.parallel().filter(map -> "motor-bike-insurance".equals(map.get("slug")))
.map(map -> map.get("id")).findFirst();
// 1000001
Object products = Stream.of(workflows.split(";")).map(
    workflow -> Stream.of(workflow.split(",")).map(pair -> pair.split(":"))
    .collect(Collectors.toMap(pair -> pair[0], pair->pair[1]))
)
.parallel().filter(map -> "motor-bike-insurance".equals(map.get("slug")))
.map(map -> map.get("id")).findFirst().orElseGet(()-> null);

// null
Object products = Stream.of(workflows.split(";")).map(
    workflow -> Stream.of(workflow.split(",")).map(pair -> pair.split(":"))
    .collect(Collectors.toMap(pair -> pair[0], pair->pair[1]))
)
.parallel().filter(map -> "motor-boat-insurance".equals(map.get("slug")))
.map(map -> map.get("id")).findFirst().orElseGet(()-> null);

System.out.println(String.format("%s", products));

Example » Predication

boolean anyMatch  = nephews.stream().anyMatch( nephew -> "Anika".equals(nephew.get("name")));
boolean noneMatch = nephews.stream().noneMatch(nephew -> "Raida".equals(nephew.get("name")));
boolean allMatch  = nephews.stream().allMatch( nephew -> nephew.get("name").startsWith("A"));

Example » Filter

List<Map<String, String>> filter = nephews.stream().filter(nephew -> nephew.get("name").startsWith("A")).collect(Collectors.toList());

List<String> names = nephews.stream().map(nephew -> nephew.get("name")).collect(Collectors.toCollection(ArrayList::new));
List<String> names = nephews.stream().map(nephew -> nephew.get("name")).collect(Collectors.toList());

Example » Sorted

names.stream().forEach(System.out::println);
names.stream().forEachOrdered(System.out::println);
names.stream().sorted().forEach(System.out::println);
names.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);

References