Last active
April 29, 2022 08:37
-
-
Save faizakram/c38c0d2a59820e6bf01d7e6afd26fd69 to your computer and use it in GitHub Desktop.
Some Java Lamda Expression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#======================== Composite Key Group By ================================= | |
Function<UserInfo, List<Object>> compositeKey = userInfo -> | |
Arrays.<Object>asList(userInfo.getName(), userInfo.getId()); | |
Map<Object, List<UserInfo>> map = userInfos.stream().collect(Collectors.groupingBy(compositeKey, Collectors.toList())); | |
#=================================================== | |
Integer arr[] = { 5, 5, 1, 2, 3, 2, 1, 1 }; | |
List<Integer> data = Stream.of(arr).collect(Collectors.toList()); | |
System.out.println("Move Data into List"+data); | |
List<Integer> sortedData = Stream.of(arr).sorted().collect(Collectors.toList()); | |
System.out.println("Sorted "+ sortedData); | |
List<Integer> sortedDataRev = Stream.of(arr).sorted(Comparator.reverseOrder()) | |
.collect(Collectors.toList()); | |
System.out.println("Reverse " +sortedDataRev); | |
Map<Integer, Integer> frequency = Stream.of(arr).collect(Collectors.toMap(m -> m, m -> 1, Integer::sum)); | |
System.out.println("Frequency" + frequency); | |
Integer sum = Stream.of(arr).reduce(0, Integer::sum); | |
System.out.println("Sum "+sum); | |
Integer min = Stream.of(arr).min(Comparator.comparing(Integer::valueOf)).get(); | |
System.out.println("Min "+min); | |
Integer max = Stream.of(arr).max(Comparator.comparing(Integer::valueOf)).get(); | |
System.out.println("Max "+max); | |
//================================ Max Age ================== | |
Person alex = new Person("Alex", 23); | |
Person john = new Person("John", 40); | |
Person peter = new Person("Peter", 32); | |
List<Person> people = Arrays.asList(alex, john, peter); | |
// then | |
Person maxByAge = people | |
.stream().max(Comparator.comparing(Person::getAge)) | |
.orElseThrow(NoSuchElementException::new); | |
System.out.println(maxByAge); | |
// OR | |
Person maxByAgeExp2 = Collections.max(people, Comparator.comparing(Person::getAge)); | |
System.out.println(maxByAgeExp2); | |
// Muliple Comparing Example | |
Person maxByAgeExp3 = Collections.min(people, Comparator.comparing(Person::getAge).thenComparing(Person::getName)); | |
//============================= Java 8: From Group By with limited List ============================ | |
private static <T> Collector<T, ?, List<T>> limitingList(int limit) { | |
return Collector.of(ArrayList::new, (l, e) -> { | |
if (l.size() < limit) | |
l.add(e); | |
}, (l1, l2) -> { | |
l1.addAll(l2.subList(0, Math.min(l2.size(), Math.max(0, limit - l1.size())))); | |
return l1; | |
}); | |
} | |
List<User> users = GenrateUserData.genrateData(); | |
// Way 1 | |
Map<String, List<User>> user = users.stream().collect(Collectors.groupingBy(User::getAddress, limitingList(2))); | |
System.out.println("Way One"); | |
System.out.println(user); | |
list.stream().collect(Collectors.groupingBy(DSCCtmLatestStatusDto::getStatus, | |
() -> new TreeMap<>(String.CASE_INSENSITIVE_ORDER), Collectors.toList())); | |
// Way 2 | |
final int N = 5; | |
Map<String, List<User>> groupByUsers = users.stream().collect(Collectors.groupingBy(User::getAddress)); | |
// Create a new stream and limit the result | |
groupByUsers = groupByUsers.entrySet().stream().limit(N) | |
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue())); | |
System.out.println(groupByUsers); | |
//============================= Java 8: From List Object to Get String Value in Comma Separated ============================ | |
String categoryNames =slClientProduct.getSlClientProductCategories().stream() | |
.filter(f -> !f.getIsDeleted()).map(m -> m.getSlCategory().getName()) | |
.collect(Collectors.joining(CommonConstants.COMMA + CommonConstants.SPACE)); //Output:- abc, xyz, obj | |
String categoryNames =slClientProduct.getSlClientProductCategories().stream() | |
.filter(f -> !f.getIsDeleted()).map(m -> m.getSlCategory().getName()).map(String::toUpperCase) | |
.collect(Collectors.joining(CommonConstants.COMMA + CommonConstants.SPACE)); //Output:- ABC, XYZ, OBJ | |
//====================================== Match String Return True/False============================= | |
String str1 = "a, b, c, d"; | |
List<String> list = Arrays.asList(str1.split(",")); | |
System.out.println(list.stream().noneMatch(str -> str.trim().equalsIgnoreCase("f"))); // None Match true | |
System.out.println(list.stream().anyMatch(str -> str.trim().equalsIgnoreCase("f"))); // Any Match false | |
//======================================= Get List of Ids =========================================== | |
List<Employee> emp = new ArrayList<Employee>(); | |
emp.add(new Employee(1L,"Faiz")); | |
emp.add(new Employee(2L,"Tanu")); | |
emp.add(new Employee(3L,"Faiz")); | |
System.out.println(emp.stream().map(m -> m.getId()).collect(Collectors.toSet())); // Output [1, 2, 3] | |
//======================================= Convert String to Long ================================================== | |
String roleIds = "1,2,3"; | |
List<Long> list = Arrays.stream(roleIds.split(",")).map(Long::valueOf).collect(Collectors.toList()); | |
System.out.println(list); // Output [1, 2, 3] | |
//======================================= Map into Custom Class with specific validtion ============================== | |
List<CutomClass> list = client.getSlClientHierarchies().stream() | |
.filter(e -> e.getIsDeleted() == CommonConstants.ZERO_BYTE) | |
.map(map -> new CutomClass(map.getId(), map.getClientHierarchyChild())).collect(Collectors.toList()); | |
//============================================== Convert Class into Map using Java 8 ========================================= | |
//List to Map with Key Mapper and Value Mapper | |
List<String> list = new ArrayList<>(); | |
list.add("Faiz"); | |
list.add("Akram"); | |
list.add("Ankur"); | |
Map<String, Object> map = list.stream().collect(Collectors.toMap(Function.identity(), s->s)); | |
map.forEach((x, y) -> System.out.println("Key: " + x +", value: "+ y)); | |
//Output | |
/*Key: Faiz, value: Faiz | |
Key: Akram, value: Akram | |
Key: Ankur, value: Ankur */ | |
//ist to Map with Key Mapper, Value Mapper on Class | |
List<Person> list = new ArrayList<>(); | |
list.add(new Person(100, "Faiz")); | |
list.add(new Person(200, "Akram")); | |
list.add(new Person(300, "Ankur")); | |
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName)); | |
//This will handle duplication value | |
Map<Integer, String> studentsMap = list.stream().collect(Collectors.toMap(Person :: getId, Person :: getName | |
, (oldValue, newValue) -> oldValue)); | |
map.forEach((x, y) -> System.out.println("Key: " + x +", value: "+ y)); | |
//Output | |
/* | |
Key: 100, value: Faiz | |
Key: 200, value: Akram | |
Key: 300, value: Ankur */ | |
//List to Map with Key Mapper, Value Mapper and Merge Function | |
List<Person> list = new ArrayList<>(); | |
list.add(new Person(100, "Faiz")); | |
list.add(new Person(100, "Akram")); | |
list.add(new Person(300, "Ankur")); | |
Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName, (x, y) -> x+", "+ y)); | |
map.forEach((x, y) -> System.out.println("Key: " + x +", value: "+ y)); | |
//Output | |
/*Key: 100, value: Faiz, Akram | |
Key: 300, value: Ankur */ | |
// List to Map with Key Mapper, Value Mapper, Merge Function and Map Supplier | |
List<Person> list = new ArrayList<>(); | |
list.add(new Person(100, "Faiz")); | |
list.add(new Person(100, "Akram")); | |
list.add(new Person(300, "Ankur")); | |
LinkedHashMap<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName, (x, y) -> x+", "+ y, LinkedHashMap::new)); | |
map.forEach((x, y) -> System.out.println("Key: " + x +", value: "+ y)); | |
//Output | |
/*Key: 100, value: Faiz, Akram | |
Key: 300, value: Ankur */ | |
//============================================== Get Index or object list in to Map<key, value>============================================ | |
List<Integer> numbers = Arrays.asList(10, 2, 3, 4, 5, 6); | |
numbers.sort(Comparator.reverseOrder()); | |
Map<Object, Object> map = numbers.stream().collect(Collectors.toMap(i -> i, i -> numbers.indexOf(i))); | |
Map<Integer, Student> map =(Map<Integer, Student>) al.stream() | |
.collect(Collectors.toMap(Student::getRollno, s->s)); //set key or object | |
//===============================================Group By Example =============================================== | |
Map<String, Integer> sum = list.stream().collect( | |
Collectors.groupingBy(User::getName, Collectors.summingInt(User::getAge))); // Sum of age output {Vijay=25, Dinesh=68, Kamal=15} | |
Map<String, Double> sum = list.stream().collect( | |
Collectors.groupingBy(User::getName, Collectors.averagingInt(User::getAge))); // Average output {Vijay=25.0, Dinesh=22.666666666666668, Kamal=15.0} | |
Map<String, Long> sum = list.stream().collect( | |
Collectors.groupingBy(User::getName, Collectors.counting())); // Count output {Vijay=1, Dinesh=3, Kamal=1} | |
//================================ Simple Sorting =================================================== | |
Collections.sort(emp, new CompartorExmaple().reversed()); // For reverse soring listing | |
emp.sort(Comparator.comparing(Employee:: getCity)); | |
emp.sort(Comparator.comparing(Employee:: getCity).thenComparing(Employee::getName)); | |
//===============================================String Date sorting ========================================= | |
List<String> date = Arrays.asList("2015-11-09", "2015-11-11", "2015-11-08", "2015-11-08"); | |
List<LocalDate> convetedSortedDate = date.stream().map(LocalDate::parse).sorted().collect(Collectors.toList()); | |
//================================================ Sort a List of Strings Alphabetically ============================== | |
List<String> cities = Arrays.asList("Milan", "london", "San Francisco", "Tokyo", "New Delhi"); | |
System.out.println(cities); | |
//[Milan, london, San Francisco, Tokyo, New Delhi] | |
cities.sort(String.CASE_INSENSITIVE_ORDER); | |
System.out.println(cities); | |
//[london, Milan, New Delhi, San Francisco, Tokyo] | |
cities.sort(Comparator.naturalOrder()); | |
System.out.println(cities); | |
//[Milan, New Delhi, San Francisco, Tokyo, london] | |
//================================================== Sort a List of Integers ========================================== | |
List<Integer> numbers = Arrays.asList(6, 2, 1, 4, 9); | |
System.out.println(numbers); //[6, 2, 1, 4, 9] | |
numbers.sort(Comparator.naturalOrder()); | |
System.out.println(numbers); //[1, 2, 4, 6, 9] | |
//========================================== Sort a List by Double Field ============================================ | |
List<Movie> movies = Arrays.asList( | |
new Movie("Lord of the rings", 8.8), | |
new Movie("Back to the future", 8.5), | |
new Movie("Carlito's way", 7.9), | |
new Movie("Pulp fiction", 8.9)); | |
movies.sort(Comparator.comparingDouble(Movie::getRating) | |
.reversed()); | |
movies.forEach(System.out::println); | |
//========================= For remove inside the list ========================================== | |
List<Employee> emp = new ArrayList<Employee>(); | |
emp.add(new Employee(1,"Faiz","Delhi")); | |
emp.add(new Employee(2,"Tanu","Noida")); | |
emp.add(new Employee(3,"Faiz","Delhi")); | |
emp.removeIf(employee -> employee.getCity().equals("Delhi")); | |
//===================================== Simple iterator using java 8 ==================================== | |
emp.forEach(emp1 ->System.out.println(emp1)); | |
emp.forEach(System.out::println); | |
//================================ Count with filter using java 8 ========================= | |
List<String> numbers = Arrays.asList("10", "2", "3", "4", "5", "6"); | |
Integer count1 = (int) numbers.stream().map(m -> Integer.valueOf(m)).filter(f -> f > 4 ).count(); | |
Integer count2 = (int) numbers.stream().map(m -> Integer.valueOf(m)).filter(f -> f > 4 && f < 6).count(); | |
//======================================= Filter Java 8 ============================= | |
List<String> lines = Arrays.asList("spring", "node", "faiz"); //String list | |
List<String> result = str.stream().filter(str -> !"faiz".equals(str)).collect(Collectors.toList()); | |
long sum = emp.stream().filter(e->e.getId() >= 1 && e.getId() < 3).mapToLong(u -> u.getSalary()).sum(); | |
System.out.println(sum); | |
int num = list.stream().filter(u -> u.getName().endsWith("sh")).mapToInt(u -> u.getSalary()).sum(); | |
System.out.println(num); | |
List<Integer> list = Arrays.asList(3, 12, 23, 44, 20, 10, 17, 8); | |
System.out.println("---List with even Numbers---"); | |
List<Integer> evenList = list.stream().filter(i -> i%2 == 0).collect(Collectors.toList()); | |
evenList.forEach(s -> System.out.print(s+" ")); | |
System.out.println("\n---List with odd Numbers---"); | |
List<Integer> oddList = list.stream().filter(i -> i%2 == 1).collect(Collectors.toList()); | |
oddList.forEach(System.out::println); | |
//====================================== Filter Name in List of User object =============================== | |
String[] name= {"Faiz", "Akram"}; | |
List<User> present = Arrays.asList(name).stream().flatMap(x -> list .stream().filter(y -> x.equalsIgnoreCase(y.getName()))) | |
.collect(Collectors.toList()); | |
//========Map Example ===================== | |
Map<String, Integer> items = new HashMap<>(); | |
items.put("A", 10); | |
items.put("B", 20); | |
items.put("C", 30); | |
items.put("D", 40); | |
items.put("E", 50); | |
items.put("F", 60); | |
items.forEach((k,v)->System.out.println("Item : " + k + " Count : " + v)); | |
items.forEach((k,v)->{ | |
System.out.println("Item : " + k + " Count : " + v); | |
if("E".equals(k)){ | |
System.out.println("Hello E"); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
add map