@FunctionalInterface
public interface GenericFunctionalInterface {
public <T> T genericMethod();
}
Run Code Online (Sandbox Code Playgroud)
我有@FunctionalInterface,它有一个通用的方法.
如何使用和Lambda表达式来表示此接口?
我尝试下面的代码,但它不起作用,
GenericFunctionalInterface gfi = () -> {return "sss";};
Run Code Online (Sandbox Code Playgroud)
我遇到了编译错误:非法的lambda表达式:GenericFunctionalInterface类型的方法genericMethod是通用的
我在哪里可以放置类型信息?
我对该方法参考语法有些困惑。
counter()预计一BiFunction不过HighTemp::lessThanTemp是,尽管有效的参数HighTemp.lessThanTemp()只带一个参数。
该行中到底发生了if (f.func(vals[i], v))什么?
MCVE:
import java.util.function.BiFunction;
class Demo {
static class HighTemp {
private int hTemp;
HighTemp(int ht) { hTemp = ht; }
boolean lessThanTemp(HighTemp ht2) {
return hTemp < ht2.hTemp;
}
}
static <T> int counter(T[] vals, BiFunction<T,T,Boolean> f, T v) {
int count = 0;
for (int i=0; i < vals.length; i++) {
if (f.apply(vals[i], v)) { // THIS LINE
count++;
}
}
return count;
}
public …Run Code Online (Sandbox Code Playgroud) 我知道java中的lambda不能抛出一个已检查的异常,但可以抛出RuntimeException,但为什么下面的代码需要括号?
Map<String, Integer> m = new HashMap<>();
Integer integer = m.computeIfAbsent("", s -> {throw new IllegalArgumentException("fail");});
Run Code Online (Sandbox Code Playgroud)
你为什么不能拥有?
m.computeIfAbsent("", s -> throw new IllegalArgumentException("fail"));
Run Code Online (Sandbox Code Playgroud)
是因为编译器假设它会在这个实例中返回一个int,所以即使抛出它也不能返回异常?
我正在尝试创建一个包含活动和该活动总持续时间的地图,因为该活动在不同持续时间下会出现更多次。
通常,我会这样解决:
Map<String,Duration> result2 = new HashMap<String,Duration>();
for(MonitoredData m: lista)
{
if(result2.containsKey(m.getActivity())) result2.replace(m.getActivity(),result2.get(m.getActivity()).plus(m.getDuration()));
else result2.put(m.getActivity(), m.getDuration());
}
Run Code Online (Sandbox Code Playgroud)
但是我试图通过流来做到这一点,但是我不知道如何将总和放入其中。
Function<Duration, Duration> totalDuration = x -> x.plus(x);
Map<String, Duration> result2 = lista.stream().collect(
Collectors.groupingBy(MonitoredData::getActivity,
Collectors.groupingBy(totalDuration.apply(), Collectors.counting()))
);
Run Code Online (Sandbox Code Playgroud)
我尝试了各种方式将它们分组,直接映射或直接将它们汇总在方括号中,但我陷入了困境。
public static void main(String o[]) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("a", 1);
map.entrySet().stream().sorted(Comparator.comparing(Entry::getValue)).forEach(System.out::println);
}
Run Code Online (Sandbox Code Playgroud)
上面的代码构建和运行完美但不应该.Comparator.comparing采用函数引用,只有那些接受一个参数并返回一个参数的方法才能映射到此.但是在上面的代码中,getValue被映射并且工作正常但它不带任何参数.代码应该给出构建问题,但不是.我的概念有什么问题吗?
在C#的LINQ,GroupBy返回IEnumerable的IGrouping项目,而这又是一个IEnumerable所选择的值的类型的项目。这是一个例子:
var namesAndScores = new Dictionary<string, int>> {
["David"] = 90,
["Jane"] = 91,
["Bill"] = 90,
["Tina"] = 89)
};
var IEnumerable<IGrouping<int, string>> namesGroupedByScore =
namesAndScores
.GroupBy(
kvp => kvp.Value,
kvp => kvp.Key
);
// Result:
// 90 : { David, Bill }
// 91 : { Jane }
// 89 : { Tina }
Run Code Online (Sandbox Code Playgroud)
具体来说,请注意,每个IGrouping<int, string>都是IEnumerable<string>和不是List<string>。(它也有一个.Key属性。)
该GroupBy显然有但是完全列举输入项目,才可以发出一个分组,因为它发出IEnumerable<string>,而不是一个 …
我喜欢在调试器中看到剪贴板符号:(U + 1F4CB).
Whearat:
我喜欢详细格式化以在Unicode中的debug-tooltip中查看它.
我当前的detail-formatter(Preferences-> Java-Debug-> Detail Formatter)是:
new String(this.getBytes("utf8"), java.nio.charset.Charset.forName("utf8")).concat(" <---")
Run Code Online (Sandbox Code Playgroud)
(上面的代码只是添加<---到详细信息视图)
在黄色工具提示中,我需要使用什么格式器才能正确显示字符?
import java.nio.charset.Charset;
public class Test {
public static void main(String[] args) {
byte[] db = new byte[] { -16, -97, -109, -117 };
String x = new String(db, Charset.forName("utf8"));
System.out.println(x);
return;
}
}
Run Code Online (Sandbox Code Playgroud) 我正在尝试从基于多个属性的学生对象列表中删除重复项,同时保留顺序,如下所示,我有学生对象列表,其中我们有多个同名但出席率不同的学生......我需要删除重复项具有相同名称且学生出席人数为 100 的学生,同时保留顺序。
Student{studentId=1, studentName='Sam', studentAttendence=100, studentAddress='New York'}
Student{studentId=2, studentName='Sam', studentAttendence=50, studentAddress='New York'}
Student{studentId=3, studentName='Sam', studentAttendence=60, studentAddress='New York'}
Student{studentId=4, studentName='Nathan', studentAttendence=40, studentAddress='LA'}
Student{studentId=5, studentName='Ronan', studentAttendence=100, studentAddress='Atlanta'}
Student{studentId=6, studentName='Nathan', studentAttendence=100, studentAddress='LA'}
Run Code Online (Sandbox Code Playgroud)
删除重复项后的愿望输出:
Student{studentId=2, studentName='Sam', studentAttendence=50, studentAddress='New York'}
Student{studentId=3, studentName='Sam', studentAttendence=60, studentAddress='New York'}
Student{studentId=4, studentName='Nathan', studentAttendence=40, studentAddress='LA'}
Student{studentId=5, studentName='Ronan', studentAttendence=100, studentAddress='Atlanta'}
Run Code Online (Sandbox Code Playgroud)
我现在所拥有的只是根据名称删除重复项而不考虑百分比(100)......并且也不保留订单......非常感谢任何帮助。(学生供应商是学生名单的简单供应商功能)
studentsSupplier.get().stream()
.sorted(Comparator.comparing(Student::getStudentName))
.collect(Collectors.collectingAndThen(
Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(Student::getStudentName))), ArrayList::new));
Run Code Online (Sandbox Code Playgroud)
注意:只有学生姓名匹配且百分比为100的重复记录必须删除,(记录Ronon有百分比100但没有重复的学生姓名相同,因此不能删除)
gc.log显示Prepare TLABs阶段花费了大约 57 秒,这是不可接受的。而且,这种情况五天才发生一次。我只想弄清楚究竟发生了什么以及如何避免。
[gc.log]
[2021-08-02T11:38:38.134+0800][322490.377s][161325][safepoint ] Entering safepoint region: G1CollectForAllocation
[2021-08-02T11:38:38.134+0800][322490.378s][161325][gc,start ] GC(238) Pause Young (Normal) (G1 Evacuation Pause)
[2021-08-02T11:38:38.134+0800][322490.378s][161325][gc,task ] GC(238) Using 18 workers of 18 for evacuation
[2021-08-02T11:39:35.179+0800][322547.422s][161325][gc,phases ] GC(238) Pre Evacuate Collection Set: 0.1ms
[2021-08-02T11:39:35.179+0800][322547.422s][161325][gc,phases ] GC(238) Prepare TLABs: 57039.1ms
[2021-08-02T11:39:35.179+0800][322547.422s][161325][gc,phases ] GC(238) Choose Collection Set: 0.0ms
[2021-08-02T11:39:35.179+0800][322547.422s][161325][gc,phases ] GC(238) Humongous Register: 0.1ms
[2021-08-02T11:39:35.179+0800][322547.422s][161325][gc,phases ] GC(238) Evacuate Collection Set: 3.8ms
[2021-08-02T11:39:35.179+0800][322547.422s][161325][gc,phases ] GC(238) Ext Root Scanning (ms): Min: 0.0, Avg: 0.4, Max: 3.5, …Run Code Online (Sandbox Code Playgroud) I have two subclasses of a class. Now I have a list that can contain either of the subclasses.
Now I need to iterate through the list and get the first occurrence of Subclass B.
I have used the below and looking for Java 8/stream/lambda way of doing this.
SeniorEmployee sEmp = null;
for(Employee emp: empList){
if(emp instanceof SeniorEmployee)
sEmp = emp;
break;
}
Run Code Online (Sandbox Code Playgroud) java ×9
java-8 ×6
java-stream ×4
lambda ×3
collections ×1
collectors ×1
dictionary ×1
duplicates ×1
eclipse ×1
function ×1
g1gc ×1
generics ×1
grouping ×1
interface ×1
java-11 ×1
jdb ×1
jvm ×1