Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
84 views
in Technique[技术] by (71.8m points)

java - Compare list of Object with Map Key and Replace the Value of list value with Map Value

This is the class which has details,

public class TestMap {


public static void main(String[] args) {
    // TODO Auto-generated method stub
    

    List<PersonData>  personDataLst = new ArrayList<PersonData>();
    
    Person person = new Person();
    Person person00 = new Person();
    
    person.setFirstName("AASH");
    person.setLastName("17072017");
    person00.setFirstName("LAKSH");
    person00.setLastName("11222020");
    
    PersonData personData = new PersonData();
    PersonData personData01 = new PersonData();
    personData01.setPerson(person00);
    personData.setPerson(person);
    personDataLst.add(personData01);
    personDataLst.add(personData);
    
    PersonResponse response = new PersonResponse();
    
    response.setPersonDatas(personDataLst);
    
    System.out.println(response.getPersonDatas().size());
    
    List<PersonData> list = response.getPersonDatas();
    
    Map<String , String> someHashMap = new HashMap<String , String>();
    someHashMap.put("17072017", "DateOfBirth");
    
    List<String> filteredLst = someHashMap.entrySet().stream()
            .filter(e -> list.contains(e.getKey()))
            .map(Map.Entry::getValue)
            .collect(Collectors.toList());
    System.out.println("******"+filteredLst);
}
}

I am trying to check whether the list contains map key , If match replace with the map value. The code I have written does return an empty list.

question from:https://stackoverflow.com/questions/65913715/compare-list-of-object-with-map-key-and-replace-the-value-of-list-value-with-map

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If the date of birth is stored in the last name property (which is a strange choice), the filtering should be as follows:

List<String> filteredLst = someHashMap.entrySet().stream()
        .filter(e -> list.stream()
                         .map(p->p.getPerson().getLastName())
                         .anyMatch(lastname -> lastname.equals(e.getKey())))
        .map(Map.Entry::getValue)
        .collect(Collectors.toList());

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...