[英]How to get an String and the ArrayList stored in a Arraylist of objects of a class using Java stream
I have modified the code and trying to get an ArrayList and the String stored in an Arraylist of Objects on a specific condition(say 'str' string equal to 2). 我已经修改了代码,并尝试在特定条件下(例如'str'字符串等于2)获取ArrayList和存储在对象的Arraylist中的字符串。 I'm not able to convert the Stream to ArrayList.
我无法将Stream转换为ArrayList。 Please help me understand what needs to be done to get the ArrayList from this stream.
请帮助我了解从该流中获取ArrayList需要做什么。
I have a class 'SampleClass' like below: 我有一个类“ SampleClass”,如下所示:
import java.util.ArrayList;
public class SampleClass {
String str;
ArrayList<String> al;
String check;
public SampleClass(String str, ArrayList<String> al, String check) {
super();
this.str = str;
this.al = al;
this.check = check;
}
public String getStr() {
return str;
}
public void setStr(String str) {
this.str = str;
}
public ArrayList<String> getAl() {
return al;
}
public void setAl(ArrayList<String> al) {
this.al = al;
}
public String getCheck() {
return check;
}
public void setCheck(String check) {
this.check = check;
}
}
I have another class 'GetTheArrayListStoredInAnotherArrayList' like below where I'm trying to get the ArrayList stored inside the ArrayList of objects. 我有另一个类“ GetTheArrayListStoredInAnotherArrayList”,如下所示,在这里我试图获取存储在对象ArrayList中的ArrayList。 Please correct me where I'm wrong.
请纠正我错的地方。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
public class GetTheArrayListStoredInAnotherArrayList{
public static void main(String[] args) {
String test = "qw,rer,try,try,erh5,wertgw45t,45";
ArrayList<String> al = new ArrayList<String>();
al.addAll(new ArrayList<String>(Arrays.asList(test.split(","))));
System.out.println(al);
ArrayList<SampleClass> sca = new ArrayList<SampleClass>();
SampleClass sc1 = new SampleClass("1", al,"ch1");
SampleClass sc2 = new SampleClass("2", al,"cc2");
SampleClass sc3 = new SampleClass("3", al,"fr3");
SampleClass sc4 = new SampleClass("4", al,"fg4");
sca.add(sc1);
sca.add(sc2);
sca.add(sc3);
sca.add(sc4);
ArrayList<String> als1 = null;
ArrayList<String> als = sca.stream().filter( s -> s.getStr().equals("2")).flatMap(sc -> sc.getAl().stream()).collect(Collectors.toCollection(ArrayList::new));
System.out.println(als);
String ch = (String) sca.stream().filter(s -> s.getStr().equals("1")).map(ac -> ac.getCheck());
System.out.println(ch);
}
}
I got the below error when I executed the code : 执行代码时出现以下错误:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Cannot cast from Stream<String> to String
at GetTheArrayListStoredInAnotherArrayList.main(GetTheArrayListStoredInAnotherArrayList.java:24)
Not entirely sure what you are trying to do, but you need to change your code a bit: 不能完全确定您要做什么,但是您需要稍微更改代码:
List<String> als = sca.stream()
.filter(s -> s.getStr().equals("2"))
.flatMap(sc -> sc.getAl().stream())
.collect(Collectors.toList());
A few things : 一些东西 :
flatMap
must return a Stream
(in your case you are returning a List
) flatMap
必须返回Stream
(在您的情况下,您将返回List
)
Collectors.toList
makes no guarantee of the List
in returns, so the assignment is to a List
, not an ArrayList
. Collectors.toList
不保证返回的List
,因此分配是给List
而不是ArrayList
。
EDIT 编辑
This: 这个:
Stream<String> stream = sca.stream().filter(s -> s.getStr().equals("1"))
.map(ac -> ac.getCheck());
Will produce a Stream<String>
. 将产生一个
Stream<String>
。 You can't simply cast that to a String
, you have to collect/reduce that to whatever you want. 您不能简单地将其转换为
String
,而必须将其收集/减少为所需的任何内容。 Like let's say a List
: 就像说一个
List
:
List<String> list = sca.stream()
.filter(s -> s.getStr().equals("1"))
.map(ac -> ac.getCheck())
.collect(Collectors.toList());
Or a single String
for example: 或单个
String
,例如:
String r = sca.stream()
.filter(s -> s.getStr().equals("1"))
.map(ac -> ac.getCheck())
.collect(Collectors.joining(","));
This is actually basic stuff... you should really study some samples and the documentation. 这实际上是基本内容...您应该真正学习一些示例和文档。
Change 更改
ArrayList<String> als = sca.stream().filter( s -> s.getStr().equals("2")).flatMap( sc -> sc.getAl());
To 至
ArrayList<String> als = sca.get(0).getAl();
First you have to use List instead of ArrayList. 首先,您必须使用List而不是ArrayList。 So with List you code will looks like
因此,使用列表,您的代码将看起来像
List<String> als1 = null;
List<String> als = sca.stream().
filter(s -> s.getStr().equals("2")). //Comparing
map(s -> s.getAl()) // Converting List<SampleClass> to list of all al list inside all SampleClass in format List<List<Straing>>
.flatMap(ArrayList::stream) //Creating a flat list from list of list of List :: List<List<Straing>> --To--> List<String>
.collect(Collectors.toList()); // Collecting as list
I have commented this code with details. 我已详细注释了此代码。 But here if there are two SampleCalss objects in the list with str=2 then it will merge the al list of both objects.
但是这里,如果列表中有两个SampleCalss对象,其str = 2,则它将合并两个对象的al列表。 hope it will help you .
希望对您有帮助。
I'm trying to get the ArrayList stored inside the ArrayList of objects.
我正在尝试将ArrayList存储在对象的ArrayList中。
Well, the basic algorithm is as follows: Filter sca
so it only leaves elements where str
is "2" -> Get a single element from all the left over elements -> Get the al
stored inside of that element. 好吧,基本算法如下:对
sca
过滤,以便仅保留str
为“ 2”的元素->从所有剩余元素中获取单个元素->获取存储在该元素内部的al
。
You have done the first part correctly: 您已经正确完成了第一部分:
sca.stream().filter( s -> s.getStr().equals("2"))
But now you need to get a single element from the filtered result (filter can result in multiple elements being left over), so you call findFirst
: 但是现在您需要从过滤后的结果中获取单个元素(过滤器可能导致剩余多个元素),因此您可以调用
findFirst
:
.findFirst().get()
This get
call will throw an exception if there is no element left after the filter. 如果过滤器后没有剩余元素,则此
get
调用将引发异常。 If you don't want it to throw an exception, you can replace it with an orElse
call: 如果您不希望它引发异常,则可以将其替换为
orElse
调用:
.findFirst.orElse(new SampleClass("", null))
If you use orElse
, the method chain will evaluate to null
if no element with str
being "2". 如果使用
orElse
,则如果没有str
为“ 2”的元素,则方法链的评估结果将为null
。
Now you just need to get the array list by calling getAl()
: 现在,您只需要通过调用
getAl()
获取数组列表:
.getAl();
Now we combine all this together: 现在,我们将所有这些结合在一起:
ArrayList<String> als = sca.stream()
.filter( s -> s.getStr().equals("2"))
.findFirst().orElse(new SampleClass("", null)).getAl();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.