我对该Function.identity()方法的用法有疑问.
想象一下以下代码:
Arrays.asList("a", "b", "c")
.stream()
.map(Function.identity()) // <- This,
.map(str -> str) // <- is the same as this.
.collect(Collectors.toMap(
Function.identity(), // <-- And this,
str -> str)); // <-- is the same as this.
Run Code Online (Sandbox Code Playgroud)
是否有任何理由你应该使用Function.identity()而不是str->str(反之亦然).我认为第二种选择更具可读性(当然是品味问题).但是,有没有"真正的"理由为什么应该首选?
我是Java 8的新手.我仍然不深入了解API,但我已经做了一个小的非正式基准测试来比较新Streams API与优秀旧Collections的性能.
测试包括过滤一个列表Integer,并为每个偶数计算平方根并将其存储在结果List中Double.
这是代码:
public static void main(String[] args) {
//Calculating square root of even numbers from 1 to N
int min = 1;
int max = 1000000;
List<Integer> sourceList = new ArrayList<>();
for (int i = min; i < max; i++) {
sourceList.add(i);
}
List<Double> result = new LinkedList<>();
//Collections approach
long t0 = System.nanoTime();
long elapsed = 0;
for (Integer i : sourceList) {
if(i % 2 == 0){
result.add(Math.sqrt(i));
} …Run Code Online (Sandbox Code Playgroud) 可能重复:
Java:如何将List转换为Map
我有arrayList
ArrayList<Product> productList = new ArrayList<Product>();
productList = getProducts(); //Fetch the result from db
Run Code Online (Sandbox Code Playgroud)
我想将ArrayList转换为HashMap,就像这样
HashMap<String, Product> s= new HashMap<String,Product>();
Run Code Online (Sandbox Code Playgroud)
请帮我看看如何转换为HashMap.
Java 8即将发布......在学习Streams的过程中,我进入了一个关于使用一种新方法对字谜进行分组的场景.我面临的问题是我找不到使用map/reduce函数对Strings对象进行分组的方法.相反,我必须创建一个与http://docs.oracle.com/javase/tutorial/collections/streams/reduction.html中记录的类似的方式.
根据文档,我们可以简单地使用LIST.stream().collect(Collectors.groupingBy(POJO :: GET_METHOD)),这样Collectors.groupingBy()将根据使用的方法聚合地图的键.但是,这种方法似乎很难包装简单的String表示.
public class AnagramsGrouping {
static class Word {
public String original;
public Word(String word) {
original = word;
}
public String getKey() {
char[] characters = input.toCharArray();
Arrays.sort(characters);
return new String(characters);
}
public String toString() {
return original;
};
}
public static void main(String[] args) {
List<Word> words = Arrays.asList(new Word("pool"), new Word("loop"),
new Word("stream"), new Word("arc"), new Word("odor"),
new Word("car"), new Word("rood"), new Word("meats"),
new Word("fires"), new Word("fries"), new Word("night"),
new Word("thing"), …Run Code Online (Sandbox Code Playgroud) 还有一类(SomeOrders),它具有像几个字段Id,Summary,Amount,等...
要求是从对象输入中收集Id作为关键字和Summary值的值.HashMapListSomeOrder
java 8之前的代码:
List<SomeOrder> orders = getOrders();
Map<String, String> map = new HashMap<>();
for (SomeOrder order : orders) {
map.put(order.getId(), order.getSummary());
}
Run Code Online (Sandbox Code Playgroud)
如何在Java 8中实现与Lambda表达式相同的功能?
我想找到一种方法来获取下面的对象特定例程并将其抽象为一个方法,您可以传递一个类,列表和字段名来获取一个Map.如果我可以在所使用的模式上获得一般指针,或者等等,这可以让我开始朝着正确的方向前进.
Map<String,Role> mapped_roles = new HashMap<String,Role>();
List<Role> p_roles = (List<Role>) c.list();
for (Role el : p_roles) {
mapped_roles.put(el.getName(), el);
}
Run Code Online (Sandbox Code Playgroud)
这个?(伪代码)
Map<String,?> MapMe(Class clz, Collection list, String methodName)
Map<String,?> map = new HashMap<String,?>();
for (clz el : list) {
map.put(el.methodName(), el);
}
Run Code Online (Sandbox Code Playgroud)
可能吗?
我以ObservableMap<T, Foo>. 要在视图中实现这些数据,我需要以ObservableList<Foo>.
因为我需要 Map Collection 中的数据(以避免重复和其他原因),我想知道是否可以绑定这两个集合。
就像是:
ObservableMap<Integer, Foo> data = FXCollections.observableHashMap();
ObservableList<Foo> target = FXCollections.observableArrayList();
// Won't work
Bindings.bindContent(target, data.values());
Run Code Online (Sandbox Code Playgroud)
绑定,因为数据可以在运行时更改。
编辑: 使用地图值初始化列表不起作用,因为将有附加的 Foo 添加到地图中:使用字符串作为地图值的示例:
ObservableMap<Integer, String> map = FXCollections.observableHashMap();
map.put(1, "a");
map.put(2, "b");
ObservableList<String> list = FXCollections.observableArrayList(map.value());
//map = {1=a, 2=b}
//list = [a, b]
// ok
map.put(3, "c");
//map = {1=a, 2=b, 3=c}
//list = [a, b]
// no update
Run Code Online (Sandbox Code Playgroud) 我的小应用程序正在从 JSON 链接获取用户列表,然后将其存储在列表中,我想将此列表放入usersCollectionfirestore 的集合引用中
我的代码
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'dart:async';
import 'package:http/http.dart' as http;
import 'package:yat_flutter_app/main.dart';
import 'usersList.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
CollectionReference usersCollection =
FirebaseFirestore.instance.collection('users');
Future<List<User>> getUsers() async {
var data = await http
.get("https://www.json-generator.com/api/json/get/bYKKPeXRcO?indent=2");
var jasonData = json.decode(data.body);
List<User> users = [];
for (var i in jasonData) {
User user = User(i["index"], i["about"], i["name"], i["picture"],
i["company"], i["email"]);
users.add(user);
} …Run Code Online (Sandbox Code Playgroud) 我正在从请求网址中捕获参数,使用com.apache.http.NameValuePair这些参数基本上存储了这些参数List<NameValuePair>.要对这些参数进行某些检查和验证,我需要将该列表转换为HashMap<String, String>.有没有办法进行这种转换?
是否有可能转换List<Entry>为Map<Employee, Map<LocalDate, Entry>>一个lambda表达式?
public class Entry {
Employee employee;
LocalDate date;
}
Run Code Online (Sandbox Code Playgroud)
到目前为止,我想出了类似的东西:
entries.stream().collect(Collectors.toMap(Collectors.groupingBy(Entry::getEmployee), Collectors.groupingBy(Entry::getDate), Function.identity()));
Run Code Online (Sandbox Code Playgroud)
但这会产生编译错误:
no suitable method found for
toMap(java.util.stream.Collector<com.a.Entry,capture#1 of ?,java.util.Map<com.a.Employee,
java.util.List<com.a.Entry>>>??,java.util.stream.Co??llector<com.a.Entry,??capture#2 of ?,
java.util.Map<java.time.LocalDate,java.util.List<com.a.Ent?ry>>>,
java.util.func??tion.Function<java.l??ang.Object,java.lang??.Object>)
Run Code Online (Sandbox Code Playgroud)
谢谢
java ×9
java-8 ×5
hashmap ×3
java-stream ×3
lambda ×3
arraylist ×2
list ×2
anagram ×1
collections ×1
dart ×1
dictionary ×1
firebase ×1
flutter ×1
generics ×1
javafx ×1
javafx-8 ×1
map ×1
mapreduce ×1
performance ×1