Instantly share code, notes, and snippets.

Embed
What would you like to do?
Some Java Lamda Expression
//============================= 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));
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");
}
});
@faizakram

This comment has been minimized.

Owner

faizakram commented Oct 16, 2018

add map

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment