how to filter out values from list based on value from another list in java [closed]

I have two list List1 and List2

List1 = REEDY,VOLCALO,MEDOZO,DIGITY
List2= this.ertert=valuefdgdfg,this.value=dsdgtt, fghghtui,oppldfgdg,this.REEDY=value.dfgryrrty.uiyiyui,hkuio,wwr,ghjgfg,this.VOLCALO=value.tyutyu.dgdfgd,
ttutyut,this.DIGITY=value.ytyutyfgh

i want to create a third list from list2 by finding corresponding values from list1 . I want to create

LIST3= this.REEDY=value.dfgryrrty.uiyiyui,this.VOLCALO=value.tyutyu.dgdfgd,this.DIGITY=value.ytyutyfgh

How can i achieve this

i tried too many things but nothing worked

  • 4

    Having a list with e.g. a string "this.DIGITY=value.ytyutyfgh" is not a good place to be. Whatever process led you to have that list needs to be revisited. his question only makes sense if that is impossible, and the correct answer in that exotic case is to first ‘fix the list’ by undoing the damage. As is, any direct answer to this question would necessarily be thoroughly ugly/unmaintainable code. (having a Map that maps DIGITY to ytyutyfgh would be fine).

    – 




  • Please show runnable code which creates the two lists.

    – 

Specifically, (correct me if I am wrong), you want to create a new List by selecting the corresponding values from List2 that match the elements in List1. See if the below code can be useful.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> List1 = List.of("REEDY", "VOLCALO", "MEDOZO", "DIGITY");
        List<String> List2 = List.of(
            "this.ertert=valuefdgdfg", "this.value=dsdgtt", "fghghtui", "oppldfgdg",
            "this.REEDY=value.dfgryrrty.uiyiyui", "hkuio", "wwr", "ghjgfg",
            "this.VOLCALO=value.tyutyu.dgdfgd", "ttutyut", "this.DIGITY=value.ytyutyfgh"
        );

        List<String> List3 = new ArrayList<>();

        for (String item : List2) {
            for (String keyword : List1) {
                if (item.contains(keyword)) {
                    List3.add(item);
                    break;  // Break the inner loop once a match is found
                }
            }
        }

        System.out.println(List3);
    }
}

Leave a Comment