Java refactor code - arraylist contains with if / else

Is it possible to refactor below if the / else part in an elegant way? Please share your experiences and feedback.

if(onlineAreaPrioList.contains("ladies")){
            dominantOnlineArea = "ladies";
        }else if(onlineAreaPrioList.contains("kids")){
            dominantOnlineArea = "kids";
        }else if(onlineAreaPrioList.contains("men")){
            dominantOnlineArea = "men";
        }else if(onlineAreaPrioList.contains("home")){
            dominantOnlineArea = "home";
        }

      

Note: Priority = Ladies> Children> Men> Home

Output : values ​​in hashmap: {men = 2, ladies = 2, home = 2, kids = 1}

values ​​in onlineAreaPrioList: [men, women, domestic]

ComputedOnlineArea: ladies

Below is the entire code:

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import dto.ProductDTO;


public class Test {

    static Map<String, Integer> freq = new HashMap<String, Integer>();

    public static void main(String[] args) {
        List<ProductDTO> recentlyBoughtList = recentlyBought();
        List<ProductDTO> recentlyViewedList = recentlyViewed();

        String finalOnlineArea = getDominantOnlineArea(recentlyViewedList,recentlyBoughtList);
        System.out.println("ComputedOnlineArea: "+finalOnlineArea);
    }

    private static String getDominantOnlineArea(List<ProductDTO> recentlyViewedList,List<ProductDTO> recentlyBoughtList) {

        for (ProductDTO productDTO:  recentlyViewedList) {
            countPrimaryOnlineArea(productDTO);
            addSecondaryOnlineAreaWithPrimary(productDTO);
        }

        for (ProductDTO productDTO:  recentlyBoughtList) {
            countPrimaryOnlineArea(productDTO);
            addSecondaryOnlineAreaWithPrimary(productDTO);
        }

        System.out.println("values in hashmap :"+freq);

        return getOnlineAreaBasedOnDefaultPriorityOrder();

    }

    private static String getOnlineAreaBasedOnDefaultPriorityOrder() {

        String dominantOnlineArea = null;
        Set<String> onlineAreaPrioList = new HashSet<String>();

        int maxValueInMap=(Collections.max(freq.values()));  
        for (Entry<String, Integer> entry : freq.entrySet()) {  
            if (entry.getValue()==maxValueInMap) {
                //System.out.println(entry.getKey());  
                onlineAreaPrioList.add(entry.getKey());
            }
        }

        System.out.println("values in onlineAreaPrioList :"+onlineAreaPrioList);

        if(onlineAreaPrioList.contains("ladies")){
            dominantOnlineArea = "ladies";
        }else if(onlineAreaPrioList.contains("kids")){
            dominantOnlineArea = "kids";
        }else if(onlineAreaPrioList.contains("men")){
            dominantOnlineArea = "men";
        }else if(onlineAreaPrioList.contains("home")){
            dominantOnlineArea = "home";
        }
        return dominantOnlineArea;
    }

    private static void countPrimaryOnlineArea(ProductDTO productDTO) {
        String pOnlineArea = productDTO.getPrimaryOnlineAreaId();
        if(OnlineAreaNotEmptyAndNotNull(pOnlineArea))
            checkAndIncreaseOnlineAreaCount(pOnlineArea);
    }

    private static boolean OnlineAreaNotEmptyAndNotNull(String onLineArea) {
        boolean onlineAreaFlag = false;
        if(null!=onLineArea)
            onlineAreaFlag = true;
        return onlineAreaFlag;
    }

    private static void addSecondaryOnlineAreaWithPrimary(ProductDTO productDTO) {
        String onlineArea = productDTO.getOnlineAreaIds();
        if(OnlineAreaNotEmptyAndNotNull(onlineArea)) {
        if(onlineArea.contains("|")) {
            String[] onlineAreaSplit = onlineArea.split("\\|");
            for(String online : onlineAreaSplit) {
                checkAndIncreaseOnlineAreaCount(online);
            }

        }else {
            checkAndIncreaseOnlineAreaCount(onlineArea);
        }
        }

    }

    private static void checkAndIncreaseOnlineAreaCount(String onlineArea) {
        int count = freq.containsKey(onlineArea) ? freq.get(onlineArea) : 0;
        freq.put(onlineArea, count + 1);
    }


    private static List<ProductDTO> recentlyBought() {
        List<ProductDTO> recentlyBoughtList= new ArrayList<ProductDTO>();

        ProductDTO productDTO1 = new ProductDTO();
        productDTO1.setPrimaryOnlineAreaId("ladies");
        productDTO1.setOnlineAreaIds("ladies");

        ProductDTO productDTO2 = new ProductDTO();
        productDTO2.setPrimaryOnlineAreaId("men");
        //productDTO2.setOnlineAreaIds("men"); //comment

        recentlyBoughtList.add(productDTO1);
        recentlyBoughtList.add(productDTO2);
        return recentlyBoughtList;
    }

    private static List<ProductDTO> recentlyViewed() {
        List<ProductDTO> recentlyViewedList= new ArrayList<ProductDTO>();

        ProductDTO productDTO1 = new ProductDTO();
        productDTO1.setPrimaryOnlineAreaId("home");
        productDTO1.setOnlineAreaIds("home");

        ProductDTO productDTO2 = new ProductDTO();
        //productDTO2.setPrimaryOnlineAreaId("men"); //comment
        productDTO2.setOnlineAreaIds("men|kids");

        recentlyViewedList.add(productDTO1);
        recentlyViewedList.add(productDTO2);
        return recentlyViewedList;
    }



}

package dto;

public class ProductDTO {
    private String primaryOnlineAreaId;
    private String onlineAreaIds;
    private String ageId;

    public String getPrimaryOnlineAreaId() {
        return primaryOnlineAreaId;
    }
    public void setPrimaryOnlineAreaId(String primaryOnlineAreaId) {
        this.primaryOnlineAreaId = primaryOnlineAreaId;
    }
    public String getOnlineAreaIds() {
        return onlineAreaIds;
    }
    public void setOnlineAreaIds(String onlineAreaIds) {
        this.onlineAreaIds = onlineAreaIds;
    }
    public String getAgeId() {
        return ageId;
    }
    public void setAgeId(String ageId) {
        this.ageId = ageId;
    }


}

      

+3


source to share


3 answers


One way is to convert the chain if

to an extended loop for

:

for (String kind : new String[] {"ladies", "kids", "men", "home"}) {
    if (onlineAreaPrioList.contains(kind)) {
        dominantOnlineArea = kind;
        break;
    }
}

      

Consider substitution "magic strings" (i.e. "ladies"

, "kids"

, "men"

and "home"

) of string constants defined at the appropriate level.



Another approach is to replace "magic strings" with enum

s, which will allow you to switch the type onlineAreaPrioList

to EnumSet

:

public enum PriorityKind {
    LADIES, KIDS, MEN, HOME 
}
...
EnumSet<PriorityKind> onlineAreaPrioList = new EnumSet<>();

      

+7


source


In fact, keeping them like this String

is probably not a good idea, since you want them to be explicitly prioritized. A definition Enum

would probably be better:

enum Priority {

    LADIES(1),
    KIDS(2),
    MEN(3),
    HOME(4);

    private final int weight;

    Priority(int weight) {
        this.weight = weight;
    }

    public int getWeight() {
        return weight;
    }
}

      



And then the usage would be:

Stream.of(Priority.KIDS, Priority.MEN)
            .max(Comparator.comparing(Priority::getWeight))
            .orElse(null);

      

+4


source


Another option is to use the Stream API, which produces a slightly more elegant solution:

dominantOnlineArea = Stream.of("ladies", "kids", "men", "home")
  .filter(onlineAreaPrioList::contains)
  .findFirst()
  .orElse(null); // handle the empty case as you wish

      

+3


source







All Articles