Filtering Arraylist - java

I have 2 array
tickets and filterTickets
I want to return new tickets that does not contain member from filterTickets.
I use this code but filter not working.
List < Ticket > a = new ArrayList <>();
for (String string: ticketsFilter) {
for (Ticket ticket: tickets) {
if (ticket.getTicketId().equals(string))
a.add(ticket);
}
}

From your description , You should have a filterTickets which is a list of strings, then you can use the follow code to check if the filterTickets contains the ticketId:
List<String> ticketsFilter = new ArrayList<>();
...
if(!ticketsFilter.contains(ticket.getTicketId())){
a.add(ticket);
}

Java 8 solution using stream API:
List<Ticket> a = tickets.stream()
.filter(e->!ticketsFilter.contains(e.getTicketId()))
.collect(Collectors.toList());

Related

How should i traverse inside two dimensional array list using for each loop

public List<String> findItinerary(List<List<String>> tickets) {
// creating adjencency list
for(String[] ticket : tickets)
{
map.putIfAbsent( ticket[0] ,new PriorityQueue<String>());
map.get(ticket[0]).add(ticket[1]);
}
dfs("JKF");
return path;
}
I m trying to create the adjacency list here, but having problem to iterate through list inside the tickets. I was using for each loop , and coming across this error "List cannot be converted to String[]
for(String[] ticket : tickets)"
You are using String[] where you should be using List<String>. Change your code to this:
for(List<String> ticket : tickets)
{
map.putIfAbsent(ticket.get(0), new PriorityQueue<String>());
map.get(ticket.get(0)).add(ticket.get(1));
}
Update
If you want to convert the List<String> in an array use this snippet:
String[] array = new String[ticket.size()];
ticket.toArray(array); // fill the array
I would suggest this way.
use computeIfAbsent which puts the value in for the key.
then it returns either the existing value or the one just entered.
then there is no need to lookup the key for insertion
public List<String> findItinerary(List<List<String>> tickets) {
// creating adjencency list
for(List<String> ticket : tickets) {
map.computeIfAbsent( ticket.get(0), v->new PriorityQueue<String>())
.add(ticket.get(1));
}
dfs("JKF");
return path;
}
As far as returning path I don't see it defined anywhere.

java sort list of strings by string value entered by a user

I am looking for a way in java to sort a list of strings based on user input in Java. for example, my list contains ["Pat Henderson", "Zach Harrington", "Pat Douglas", "Karen Walsh"], if a user enters the first name "Pat" how would I be able to print out only the Pats in the list and same for surnames?
ArrayList<String> str = new ArrayList<String>();
for(int i = 0 ; i < str.size() ; i++) {
if(str.get(i).contains("your_user_input")) {
System.out.println(str.get(i));
}
}
.filter() introduced in Java 8 would to the thing.
List<String> names = new ArrayList<>();
names.addAll(Arrays.asList("Pat Henderson", "Zach Harrington", "Pat Douglas", "Karen Walsh"));
String startsWith = "Pat";
List<String> filteredNames = names.stream()
.filter(name -> name.startsWith(startsWith))
.collect(Collectors.toList());
A little remark. Sorting is when you rearrange the position of the elements without removing any.
Supposing that each element of the list have a name and a last name separated by a whitespace or more, with Java 8 you could filter on the name or the last name in this way :
List<String> list = Arrays.asList("Pat Henderson", "Zach Harrington", "Pat Douglas", "Karen Walsh");
String nameOrLastNameToFilter = ...;
list.stream().filter(s -> Arrays.stream(s.split("\\s+"))
.anyMatch(n->n.equals(nameOrLastNameToFilter))
)
.collect(toList());

get all object from 1 list of 1 list by stream in java 8?

I have 2 classes, this:
public class TimeCardResponse {
private String login;
List<TimeCardDetail> timeCardDetails;
}
and this:
public TimeCardDetail(String workingDay, Float workingTime) {
this.workingDay = workingDay;
this.workingTime = workingTime;
}
input : a List<TimeCardResponse>
I want to get all workingDay of class TimeCardDetail in a List<String> and using Stream in Java 8.
List<String> workingDays = a.stream().map(TimeCardResponse::getTimeCardDetails)
.filter(x-> Objects::nonNull)
.flatMap(List::stream)
.map(TimeCardDetail::getWorkingDay).collect(toList());
Assuming you have some a getWorkingDay method:
List<String> workDays = timeCardDetails.stream()
.map(TimeCardDetail::getWorkingDay)
.filter(Objects::nonNull) //filter out null values
.collect(Collectors.toList());
Which will return a List<String> of the work days of the time Cards

Short way to create sub-list in java

Is there a shorter way to create sublist from other list?
For example:
I have a Contact obiect, this obiect contain String field of adres
public List<String> getAdreses(long personID) {
List<String> adreses=null;
for(Contact mail : getContacts(personID)){
adreses.add(mail.getMail());
}
return adreses;
}
Try Java Stream:
List<String> adreses = getContacts(personID).stream().map(Contact::getMail).collect(Collectors.toList())

Convert List<List<String>> to ArrayList<String> in Android

I want to convert them to ArrayList and I will store them. After that, I have to convert them into old values. Do you have any suggestions? Thanks in advance.
public List<List<String>> phones = new ArrayList<>();
public List<List<Restaurant.Menu>> menus = new ArrayList<>();
public ArrayList<String> phones = ?
public ArrayList<String> menus = ?
For the first scenario, you can flatten the phones nested list into a single list and then collect into an ArrayList.
ArrayList<String> result =
phones.stream()
.flatMap(Collection::stream)
.collect(Collectors.toCollection(ArrayList::new));
For the second scenario, you will need to extract the string representation of the Menu objects given you've overridden toString, otherwise you'll need to extract some type of property from the Menu objects in order to project from Menu to String.
Given you've overridden toString, then do it this way:
ArrayList<String> menuResult =
menus.stream()
.flatMap(Collection::stream)
.map(Menu::toString)
.collect(Collectors.toCollection(ArrayList::new));
Given you need to extract some property from menus, then do it this way:
ArrayList<String> menuResult =
menus.stream()
.flatMap(Collection::stream)
.map(Menu::getName)
.collect(Collectors.toCollection(ArrayList::new));
If your API level doesn't support these features then you can use:
// flatten List<List<String>> to ArrayList<String>
ArrayList<String> phonesAccumulator = new ArrayList<>();
for (List<String> temp : phones) {
phonesAccumulator.addAll(temp);
}
// flatten List<List<Restaurant.Menu>> to ArrayList<String>
ArrayList<String> menusAccumulator = new ArrayList<>();
for (List<Restaurant.Menu> temp : menus) {
for(Restaurant.Menu m : temp){
menusAccumulator.add(m.toString());
// or m.getName();
}
}
If you're using Java 8, flatMap can be useful here:
ArrayList<String> phoneList = phones.stream()
.flatMap(List::stream)
.collect(Collectors.toCollection(ArrayList::new));
I am proving my resolution as below said, so you can change as per your own -
List<String> nonvegList = new ArrayList<String>();
nonvegList.add("Mutton Keema");
nonvegList.add("Chicken Keema");
nonvegList.add("Korma Veg Keema");
nonvegList.add("Pulaav Biryaani");
nonvegList.add("Mutton Biryaani");
nonvegList.add("Chicken Biryaani");
List<List<String>> menuList = new ArrayList<List<String>>();
menuList.add(nonvegList);
ArrayList<String> resultList = new ArrayList<String>(menuList.get(0));
System.out.println(resultList);
sweet, simple and in understadable format, compatible after Java 6+,
hope this will help you, thanks.
I used gson to solve it. I share a sample.
Gson gson = new Gson();
ArrayList<String> gsonString = new ArrayList<>();
for(int i=0; i<restaurants.size(); i++)
gsonString.add(gson.toJson(restaurants.get(i)));
// Store it
tinydb.putListString("tinyRestaurant",gsonString);
And convert again
Gson gson = new Gson();
for(int i=0; i<tinydb.getListString("tinyRestaurant").size(); i++)
restaurants.add(gson.fromJson(tinydb.getListString("tinyRestaurant").get(i), Restaurant.class));

Categories

Resources