Temp - Yash-777/MyWorld GitHub Wiki

JOSN Object mapper

JSON To Object

File file = new File(payLoadJsonFile);
ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
//mapper.setSerializationInclusion(Include.NON_NULL);
Employee resultUser = mapper.readValue(file, new com.fasterxml.jackson.core.type.TypeReference<Employee>(){});

Object To JSON

File file = new File(payLoadJsonFile);
ObjectMapper mapper = new com.fasterxml.jackson.databind.ObjectMapper();
//mapper.setSerializationInclusion(Include.NON_NULL);
Employee resultUser = mapper.readValue(file, new com.fasterxml.jackson.core.type.TypeReference<Employee>(){});

Threads

  • execute(Runnable task):void crates new thread but not blocks main thread or caller thread as this method return void.
  • submit(Callable<?>):Future<?>, submit(Runnable):Future<?> crates new thread and blocks main thread when you are using future.get().
public interface Runnable { | public interface Callable<Object> {
    public void run();      |     public Object call() throws Exception;
}                           | }

ExecutorService executor = Executors.newFixedThreadPool(4);
  Future<?> f1r = executor.submit( new RunnableTask(5) );
  // Waits until pool-thread complete, return null upon successful completion.
  System.out.println("F1R : "+ f1r.get());

  Future<Integer> f1c = executor.submit( new CallableTask(5) );
  // Waits until pool-thread complete, returns the result.
  System.out.println("F1C : "+ f1c.get());

executor.shutdown();

Java 8

Stream API

The Streams API will internally decompose your query to leverage the multiple cores on your computer.

To summarize what we’ve learned so far, working with streams, in general, involves three things:

  • A datasource (such as a collection) on which to perform a query
  • A chain of intermediate operations, which form a stream pipeline
  • One terminal operation, which executes the stream pipeline and produces a result

Intermediate Operation: map(predicate), filter(funciton), sorted(comparator)

Comparator Comparable vs comparator, java8 lambda

Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
Collections.sort( empList, Comparator.comparing( Employee::getCreationTime )
                                     .thenComparing( Employee::getName ));

Comparator<Emp> comparingSal = Comparator.comparing( Emp::getSal );       // reversed()
Comparator<Emp> comparingName = Comparator.comparing( Emp::getName );
Comparator<Emp> thenComparing = comparingSal.thenComparing( comparingName ); // thenComparing( ... )
List<Emp> collectNames = list.stream().sorted( comparingName ).collect( Collectors.toList() );

List<Emp> collectSal = list.stream().sorted( comparingSal.reversed() )
                                    .limit(3).collect(Collectors.toList());

list.steam().collect( Collectors.maxBy( Comparator.comparingDouble( Emp::getSal ) ) );

Counts the frequencies of the given list of words.

Map<String, Long>    mapGroup = wordsList.stream().collect( Collectors.groupingBy(Function.identity(), Collectors.counting() ));
Map<String, Integer> mapGroup = wordsList.stream().collect( Collectors.groupingBy(Function.identity(), Collectors.summingInt(e -> 1) ));

boolean hasDuplicates = mapGroup.entrySet().stream().anyMatch( entry -> entry.getValue() > 1 );

List of Distinct Employees based on EMP-ID

Set<Integer> idSet = new HashSet<>();
List<Emp> employeesDistinctById = empList.stream()
            .filter(e -> idSet.add(e.getId()))
            .collect(Collectors.toList());
System.out.println(employeesDistinctById);

Employee List - Department wise max salary

Map<String, Optional<Emp>> mapMaxSalByDept= empList.stream().collect(
        Collectors.groupingBy( Emp::getDepartment, 
                //Collectors.reducing( BinaryOperator.maxBy(Comparator.comparing(Emp::getSal)) )));
                Collectors.maxBy( Comparator.comparingInt(Emp::getSal) )));

Map<String, Emp> mapMaxSalByDept2= empList.stream().collect(
        Collectors.groupingBy( Emp::getDepartment, 
                Collectors.collectingAndThen( Collectors.maxBy( Comparator.comparingInt(Emp::getSal) ), Optional::get ) ));

Map<String, Emp> topEmployees = empList.stream()
                .collect( Collectors.toMap( e -> e.department, e -> e, BinaryOperator.maxBy(Comparator.comparingInt(e -> e.sal)) ) );

Stream<Emp> mapMaxSal_Nth= empList.stream().sorted(Comparator.comparing(Emp::getSal).reversed()).limit(3).skip(2);
String str    = "Hello World";
int strLength = str.length();
IntFunction<String> reverseMapper = (i) -> Character.toString( ( str.charAt( strLength -1 - i) ) );

String reverseString = IntStream.range(0, strLength) // for (int i = 0; i < strLength ; i++) { ... }
		.mapToObj( reverseMapper )                 // array[ lastElement ]
		.collect(Collectors.joining())             // Joining stream of elements together into a String.
		.toString();                               // This object (which is already a string!) is itself returned.

int[] arr2 = {5, 6, 7, 2, 8, 0};
List<Integer> arr2List = Arrays.stream( arr2 )
		               .mapToObj( i -> i )  // int to Integer (AutoBoxing)
		               .collect(Collectors.toList());

StringJoiner joinNames = new StringJoiner(",", "[", "]");   // passing comma(,) and square-brackets as delimiter   
joinNames.add("Yash");
joinNames.add("Yash777");
Stream.of(1, 2, 3, 4, 5)          // Stream source
    .filter(x -> x % 2 == 0)      // Intermediate operation  .map(String::toUpperCase)
    .collect(Collectors.toList()) // Terminal operation      .forEach( n -> System.out.println( n.toUpperCase() ) ); .forEach( System.out::println );

Predicate<Integer>            isEven      = (value) -> value % 2 == 0;
BiPredicate<Integer, Integer> isDivisible = (a, b) -> a % b == 0;


List<Integer> list2 = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 6));
int reduceSum = list2.stream()
                     .reduce(0, (value, sum) -> sum += value); // 27
int mapSum = list2.stream()
                  .mapToInt(i -> i).sum(); // 27
long count = list2.stream()
                  .count(); // 7
Optional.ofNullable(list)
            .orElseGet(ArrayList::new)
            .stream()

Map<Integer, Long> mapRepeatedCount = list.stream()
                                          .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Map<String, List<Emp>> res = empList.stream()
                                    .collect(Collectors.groupingBy(Emp::getCountry));
        
Map<String, Map<String, List<Emp>>> res2 = empList.stream()
                                                  .collect( Collectors.groupingBy(Emp::getCountry, Collectors.groupingBy(Emp::getState) ) );

Map<Integer, String> result = map.entrySet().stream()
    //.sorted(Map.Entry.comparingByKey()) //.sorted(Map.Entry.comparingByValue())
    .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))  // HashMap
    //.sorted(Map.Entry.<String, Integer>comparingByValue().reversed()) //LinkedHashMap
    
    //.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new)); // sorted stream map
    .collect(Collectors.toMap(k -> k.getKey(), e -> (String) e.getValue())); // Normal Map

model name might appear anywhere in the review/feedback text, not just at the beginning.

List<String> model = Arrays.asList("samsung", "Iphone", "LG");
List<String> review = Arrays.asList( // Feedback
        "samsung review ...", "jjdj LG review ...", "hai samsung review ...",
        "d jjdjd LG review ...", "Iphone review ..."
        );
        
Map<String, Long> reviewCounts = review.stream()
        .filter(str -> model.stream().anyMatch(str::contains)) // keep only reviews related to models in the list
        .collect(Collectors.groupingBy(
                str -> model.stream().filter(str::contains).findFirst().get(), // extract the model name from the review text
                HashMap::new, // use a HashMap as the result map
                Collectors.counting())); // count the number of reviews for each model
System.out.println(reviewCounts); // {samsung=2, Iphone=1, LG=2}

Map<String, Long> reviewCounts2 = model.stream()
        .filter(modelName -> review.stream().anyMatch(str -> str.contains(modelName))) // keep only models that have related reviews
        .collect(Collectors.toMap(
                modelName -> modelName,
                modelName -> review.stream().filter(str -> str.contains(modelName)).count())); // count the number of reviews for each model
System.out.println(reviewCounts2); // {samsung=2, Iphone=1, LG=2}

Map<String, Long> sortedReviewCounts = reviewCounts.entrySet().stream()
        //.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
        .sorted(Map.Entry.<String, Long>comparingByValue().reversed()) // sort by value in reverse order
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
                      // put the entries in a LinkedHashMap to preserve the order

System.out.println(sortedReviewCounts); // {samsung=2, LG=2, Iphone=1}
⚠️ **GitHub.com Fallback** ⚠️