Answer the question
In order to leave comments, you need to log in
How to do dynamic method substitution?
Hello. How to do dynamic method substitution?
Object method = Ticket::getFrom;
if (prop == Properties.FROM) {
// method = Ticket::getFrom;
} else if (prop == Properties.TO) {
// method = Ticket::getTo;
}
// Как правильно динамически подставлять выражение?
// return tickets.stream()
// .collect(Collectors.groupingBy(method,
// Collectors.mapping(Function.identity(), Collectors.toList())));
package main.java;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
enum Properties {
FROM, TO,
}
public class Solution {
public Map<String, List<Ticket>> fromEntries(List<Ticket> tickets, Properties prop) {
/*
return tickets.stream()
.collect(Collectors.groupingBy(Ticket::getFrom, Collectors.mapping(Function.identity(), Collectors.toList())));
*/
// Object method = Ticket::getFrom;
if (prop == Properties.FROM) {
// method = Ticket::getFrom;
} else if (prop == Properties.TO) {
// method = Ticket::getTo;
}
// return tickets.stream()
// .collect(Collectors.groupingBy(method,
// Collectors.mapping(Function.identity(), Collectors.toList())));
}
public List<Ticket> sortingTickets(List<Ticket> tickets) {
Map<String, List<Ticket>> mapFrom = fromEntries(tickets, Properties.FROM);
System.out.println(fromEntries(tickets, Properties.FROM));
return tickets;
}
}
class Ticket {
private String from;
private String to;
public Ticket(String from, String to) {
this.from = from;
this.to = to;
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
@Override
public String toString() {
return "Ticket{" +
"from='" + from + '\'' +
", to='" + to + '\'' +
'}';
}
}
class Main {
public static void main(String[] args) {
List<Ticket> tickets = new ArrayList<>();
Ticket ticket1 = new Ticket("С.Петербург", "Минск");
Ticket ticket2 = new Ticket("Киев", "Новосибирск");
Ticket ticket3 = new Ticket("Череповец", "Москва");
Ticket ticket4 = new Ticket("Минск", "Киев");
Ticket ticket5 = new Ticket("Москва", "С.Петербург");
tickets.add(ticket1);
tickets.add(ticket2);
tickets.add(ticket3);
tickets.add(ticket4);
tickets.add(ticket5);
System.out.println(new Solution().sortingTickets(tickets));
}
}
Answer the question
In order to leave comments, you need to log in
Oh, js is immediately visible. First, you put a normal ide, namely an idea. Then you select Ticket::getTo and press options + commands + m on the poppy, and you substitute the idea for the type. In your case, Function "angle bracket" Ticket, String "angle bracket", and never an object. And in general, everything
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question