0

I have the following ArrayList:

public static List c = new ArrayList();
c = [1,2,3];

I have the following List in an ArrayList:

public static ArrayList<List<String>> Contact = new ArrayList<List<String>>();
Contact = (["One",1], ["Two", 2], ["Three",3], ["Four", 4])

How can I compare the Lists in away that I get a new list that has the value of:

["One","Two","Three"] ????

Basically: I want to check the integer, see if it exists in the second value of an item in the List, and if so, add the first item, to the new list.

3
  • so what did you do in order to achieve this? Commented Aug 5, 2018 at 8:48
  • I am asking a question! I dont know how. Commented Aug 5, 2018 at 8:48
  • how you add String and int in an List of Strings?? Commented Aug 5, 2018 at 8:49

2 Answers 2

1

Instead of creating a ArralyList>, Better to use a HashMap

Have data as

c = [1,2,3];

Map<Int, String> data = new HashMap();
data.put(1, "One");
data.put(2, "Two");
data.put(3, "Three");

ArrayList<String> output = new ArrayList()
for(int i=0 i<c.length; i++) {
    output.add(data.get(c[i]));
}

Now output will have the data ["One", "Two", "Three"]

Sign up to request clarification or add additional context in comments.

Comments

1

Ok, If in any case your code look like this :

List<Integer> c = new ArrayList(Arrays.asList(1, 2, 3));
ArrayList<List<String>> contact = new ArrayList<List<String>>();
contact.add(Arrays.asList("One", "1"));
contact.add(Arrays.asList("Two", "2"));
contact.add(Arrays.asList("Three", "3"));
contact.add(Arrays.asList("Four", "4"));

You can use streams like so :

List<String> result = contact.stream()
        .filter(l -> c.contains(Integer.valueOf(l.get(1))))
        .map(l -> l.get(0))
        .collect(Collectors.toList());

this will gives you :

[One, Two, Three]

Better Solution

Rather for a good work, I would create a class Contact which hold id and a name for example :

class Contact{
   private Integer id;
   private String name;

   //constructor getters and setters
}

Then fill your List like so :

ArrayList<Contact> contact = new ArrayList<>();
contact.add(new Contact(1, "One"));
contact.add(new Contact(2, "Two"));
contact.add(new Contact(3, "Three"));
contact.add(new Contact(4, "Four"));

So when you want to search you can use :

List<String> result = contacts.stream()
        .filter(l -> c.contains(l.getId()))
        .map(Contact::getName)
        .collect(Collectors.toList());

It can be more readable and more helpful to work.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.