我找不到使用当前对象和当前索引调用 lamda 的 forEach 方法。
不幸的是,这在 java8 中没有实现,所以下面的实现是不可能的:
List<String> list = Arrays.asList("one", "two");
list.forEach((element, index) -> System.out.println(String.format("[%d] : %s", index, element)));
Run Code Online (Sandbox Code Playgroud)
我知道一个简单的方法是使用带有索引整数的 for each 循环:
List<String> list = Arrays.asList("one", "two");
int index = 0;
for (String element : list) {
System.out.println(String.format("[%d] : %s", index++, element));
}
Run Code Online (Sandbox Code Playgroud)
我认为初始化索引整数并为每次迭代增加它的通用代码应该移到一个方法中。所以我定义了自己的forEach方法:
public static <T> void forEach(@NonNull Iterable<T> iterable, @NonNull ObjIntConsumer<T> consumer) {
int i = 0;
for (T t : iterable) {
consumer.accept(t, i++);
}
}
Run Code Online (Sandbox Code Playgroud)
我可以像这样使用它:
List<String> list = Arrays.asList("one", "two"); …Run Code Online (Sandbox Code Playgroud) 以下是我迄今为止尝试过的代码,它有效:
public static void main(String[] args) {
Random random = new Random();
Integer[] integers = random.ints(10, 100, 999).boxed().toArray(Integer[]::new);
List<Integer> list = new ArrayList<>();
for (int i = 0; i < integers.length; i++) {
String[] split = integers[i].toString().split("");
int a = 0, b = 0, c = 0;
a = Integer.valueOf(split[0]);
b = Integer.valueOf(split[1]);
c = Integer.valueOf(split[2]);
if ((a != b) && (a != c) && (b != c)) {
list.add(Integer.valueOf(integers[i]));
}
}
list.forEach(System.out::println);
}
Run Code Online (Sandbox Code Playgroud)
输出是正确的。
如果ABC是整数,然后
a !=b …
我一直在尝试重写以下内容以使用Stream API.我似乎无法弄清楚如何到Map(或字段)为System.setProperty(k,v)设置键值对
我的数据只是在它们之间有空格的行,它们分别分为键和值:
foo bar
mykey myvalue
nextkey nextvalue
Run Code Online (Sandbox Code Playgroud)
我的工作源代码在这里:
try {
Scanner scanner = new Scanner(Paths.get("/path/to/file.txt"));
while(scanner.hasNextLine()){
String line = scanner.nextLine();
String[] array = line.split(" ");
if(array.length == 2){
System.setProperty("twitter4j.oauth." + array[0], array[1]);
}
}
} catch (IOException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
在这里放一个破碎的样本,虽然我已经遍布地图(呻吟)试图用流写它,但这里只是为了证明我尝试了一次迭代:-p
Stream<String> lines = null;
try {
lines = Files.lines(Paths.get("/Users/bellis/dev/data/twitter.txt"));
} catch (IOException e) {
e.printStackTrace();
}
String[] words = lines.collect((Collectors.joining("\n"))).split(" ");
System.out.println("twitter4j.oauth." + words[0] + " " + words[1]);
Run Code Online (Sandbox Code Playgroud)
上面当然是不正确的我知道有更好的方法来使用函数和其他常见的流成语来编写它,但我似乎无法做到正确.您如何建议使用Stream和功能API编写此代码?
给定2D矩阵,任务是找到一个沙漏的最大和。
沙漏杯由以下形式的7个电池组成。
Run Code Online (Sandbox Code Playgroud)A B C D E F G
我的实施出现问题,我得到了奇怪的答案。我应该得到19,但返回36。
这是我的代码:
static int hourglassSums(int[][] arr)
{
return IntStream.range(0, 4).map(x -> {
return IntStream.range(0, 4).map(y ->
arr[y][x] + arr[y][x + 1] + arr[y][x + 2]
+ arr[y + 1][x + 1]
+ arr[y + 2][x] + arr[y + 2][x + 1] + arr[y + 2][x + 2]
).sum();
}).max().getAsInt();
}
public static void main(String[] args)
{
System.out.println("Max sum :: " + hourglassSums(new int[][] {
{1, 1, …Run Code Online (Sandbox Code Playgroud) 不寻找杰克逊解决方案。
进口清单:
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.util.List;
import java.util.stream.Collectors;
Run Code Online (Sandbox Code Playgroud)
JSON数据:
{
"Name": "ABC.com",
"Developer": "Vishwa ratna",
"Project List": [
"Compnay: National",
"Compnay: Enterprise",
"Compnay: Alamo"
]
}
Run Code Online (Sandbox Code Playgroud)
我的程序:
@SuppressWarnings("unchecked")
public static void main(String[] args)
{
File text = new File("R:/TestJSON.txt");
JSONParser parser = new JSONParser();
try {
Object obj = parser.parse(new FileReader("R:\\Desktop\\TestJSON.txt"));
JSONObject jsonObject = (JSONObject) obj;
List<String> list = new ArrayList<>();
String name = (String) jsonObject.get("Name");
System.out.println(name);
String author = …Run Code Online (Sandbox Code Playgroud) 我刚刚开始阅读Java 8概念,而我却发现一些不足以说服我的东西是Interface中缺少compose和identity方法BiFunction。就我从Java 8文档中读取的内容来看,我Bifunction似乎与Functioninterface 相同,期望它需要一个附加参数,因此在这种情况下Bifunction应该具有与Functioninterface相同的所有功能,但事实并非如此。
因此,有人可以帮助我找到省略这些方法的原因吗?
我正在尝试从orElse / orElseGet流运算符返回HashMap,但似乎无法在这些运算符中使用HashMap。
public class Main {
public static void main(String args[]) {
List<String> names = new ArrayList<String>() {{
add("test1");
}};
HashMap<Integer, String> indexToNameMap = names.stream()
.filter(name -> name.equals("test"))
.map(name -> new HashMap<Integer, String>() {{
put(names.indexOf(name), name);
}})
.findFirst()
.orElseGet(() -> new HashMap<Integer, String>() {{
put(0, "UN_AVAILABLE");
}});
}
}
Run Code Online (Sandbox Code Playgroud)
错误:
Bad return type in lambda expression: HashMap<Integer, String> cannot be converted to HashMap<Integer, String>
Run Code Online (Sandbox Code Playgroud)
如何解决这个问题?
我有一个像下面这样的课程:
public class Company {
private List<Team> teams;
}
public class Team {
String name;
}
Run Code Online (Sandbox Code Playgroud)
我有这样的Compony对象的列表:
List<Company> companies = ...
Run Code Online (Sandbox Code Playgroud)
团队可以属于并出现在多个公司的列表中。
我正在寻找使用Java流将公司分组为地图的方式,并以团队名称作为地图键。每个地图条目的值是团队所属公司的列表。像这样。
Map<String, List<Company>> companiesGroupedByTeam;
Run Code Online (Sandbox Code Playgroud)
因此,同一家公司可能会出现在不同团队的列表中。
有谁知道如何使用Java流进行分组?努力做小组。
谢谢!
假设列表firstName已被初始化。
List<String> firstName= new ArrayList<String>();
firstName.add("John");
firstName.add("Peter");
firstName.add("Foo");
Run Code Online (Sandbox Code Playgroud)
是否可以使用它在一行代码中填充另一个列表?我不知道如何在少于以下几行的情况下做到这一点:
List<FullName> fullName= new ArrayList<FullName>();
firstName.stream().forEach( n -> fullName.add(new FullName(n, "SomeSurname")));
Run Code Online (Sandbox Code Playgroud) 我有两个清单。我想创建一个映射里面会有真正的匹配部件及虚假的唯一一个在Java 8
EG。
输入 -
列表1 = [A,B,C,D]
列表2 = [B,C,Y,Z]
输出 -
地图:
A,假
B,真
C真
D,假
我的代码:
Map<String,Boolean> map = new HashMap<>();
for(String var1 : list1) {
boolean value;
if (CollectionUtils.isNotEmpty(list2)) {
Optional<String> valueOptional = list2.stream()
.filter(e1 -> e1.equalsIgnoreCase(var1))
.findAny();
value = valueOptional.isPresent();
map.put(var1, value);
}
}
Run Code Online (Sandbox Code Playgroud) java ×10
java-8 ×10
java-stream ×6
arrays ×1
collections ×1
dictionary ×1
foreach ×1
json ×1
lambda ×1