search
HomeJavaHow can I combine these two methods into one?

php editor Apple will answer your question in Java: How to combine two methods into one? In Java programming, sometimes we need to merge two methods into a more efficient method to improve the readability and execution efficiency of the code. By merging methods, duplicate code can be reduced, program structure simplified, and code reusability improved. Next, we will introduce specific operating steps and precautions to help you quickly implement method merging and optimize Java program design.

Question content

I have two very similar methods. So I want to reduce it to a method but I don't know how.

Use like this:

mapclassbtoclassa("a list o classb objs", "a list of classa objs");
mapclassctoclassa("a list o classc objs", "a list of classa objs");

I want to change to:

mapclasstoclassa("a list o classb objs", "a list of classa objs");
mapclasstoclassa("a list o classc objs", "a list of classa objs");

Method 1b => a

public void mapclassbtoclassa(list<classb> b, list<classa> a){
   comparator<classb> sortfunc = comparator.comparing(classb::getdate);
   collections.sort(b, sortfunc);
   for (classa aobj : a){
      localdate datea = aobj.getdate();
      classb bobjtouse = null;
      for (classb bobj : b){
         localdate dateb = bobj.getdate();
         if (dateb.isafter(datea)){
            break;
         }
         else {
            bobjtouse = bobj; 
         } 
      }
      if (bobjtouse != null){
         aobj.setclassb(bobjtouse);
      }
   }
}

Method 2c => a

public void mapclassctoclassa(list<classc> c, list<classa> a){
   comparator<classc> sortfunc = comparator.comparing(classc::getdate);
   collections.sort(c, sortfunc);
   for (classa aobj : a){
      localdate datea = aobj.getdate();
      classc cobjtouse = null;
      for (classc cobj : c){
         localdate datec = cobj.getdate();
         if (datec.isafter(datea)){
            break;
         }
         else {
            cobjtouse = cobj; 
         } 
      }
      if (cobjtouse != null){
         aobj.setclassc(cobjtouse);
      }
   }
}

I want to do something similar:

public void mapclasstoclassa(list< **xx** > t, list<classa> a){
   comparator< **xx** > sortfunc = comparator.comparing( **xx** ::getdate);
   collections.sort( t , sortfunc);
   for (classa aobj : a){
      localdate datea = aobj.getdate();
      **xx** objtouse = null;
      for (**xx** obj : t){
         localdate datet = obj.getdate();
         if (datet.isafter(datea)){
            break;
         }
         else {
            objtouse = bobj; 
         } 
      }
      if (objtouse != null){
         aobj.setclassxxx(objtouse);
      }
   }
}

I tried using generics

public <t> void maptoarende(list<t> t, list<classa> a){
        ...
           t objtouse = null;

But this:

  • I can't execute the comparator because this doesn't work

    comparator.comparing(t::getfromdat);
  • Instead of a call to obj.getdate(), here I found a solution using reflection, but people advise against it. But it works. what do I do?

    Method m = obj.getClass().getMethod("getDate");
    LocalDate dateT = (LocalDate) m.invoke(obj);
  • I don’t know how to call aobj.setclassxxx() because the method names of classb and classc are different

I've read about lambdas but am having some difficulty understanding how to use them.

Workaround

If you cannot add a common interface to these classes, you can add some functions to the method parameters:

public <t> void mapclasstoclassa(list<t> t, list<classa> a,
                                 function<t, localdate> dategetter,
                                 biconsumer<classa, t> setter) {

    comparator<t> sortfunc = comparator.comparing(dategetter);
    collections.sort(t, sortfunc);
    for (classa aobj : a) {
        localdate datea = aobj.getdate();
        t ttouse = null;
        for (t tobj : t){
            localdate datet = dategetter.apply(tobj);
            if (datet.isafter(datea)){
                break;
            }
            ttouse = tobj; 
        }
        setter.accept(aobj, tobjtouse);
    }
}

The call is as follows:

mapclasstoclassa(b, a, classb::getdate, classa::setclassb);
mapclasstoclassa(c, a, classc::getdate, classa::setclassc);

That’s what interfaces are for, isn’t it?

public interface dated {
  localdate getdate();
} 

public class classb implements dated {
  ...
}

public class classc implements dated {
  ...
}

For setters, you can use instanceof.

public void mapClassBToClassA(List<? extends Dated> b, List<ClassA> a){
   Comparator<Dated> sortFunc = Comparator.comparing(Dated::getDate);
   Collections.sort(b, sortFunc);
   for (ClassA aObj : a){
      LocalDate dateA = aObj.getDate();
      Dated datedToUse = null;
      for (Dated bObj : b){
         LocalDate dateB = bObj.getDate();
         if (dateB.isAfter(dateA)){
            break;
         }
         else {
            datedToUse = bObj; 
         } 
      }
      if (datedToUse instanceOf ClassB bObjToUse) {
         aObj.setClassB(bObjToUse);
      }
      else if (datedToUse instanceOf ClassC cObjToUse) {
         aObj.setClassC(cObjToUse);
      }
   }
}

The above is the detailed content of How can I combine these two methods into one?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:stackoverflow. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.