简体   繁体   English

如何使用Java流获取字符串和存储在类对象的Arraylist中的ArrayList

[英]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();

如何转换 ArrayList<string> 至 ArrayList<object> using.collect(Collectors.toList() 在 Java stream<div id="text_translate"><p> 如何在 Java stream 中使用.collect(Collectors.toList()将ArrayList&lt;String&gt;转换为ArrayList&lt;Object&gt;</p><p> 之前我用过</p><pre>CommonList = detailUtils.SelectIDValueGetterObservable(getActivity()).stream().forEach(i -&gt; CommonList.add(new foo(i));`</pre><p> 但是我遇到了这些<strong>副作用</strong></p><p> <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html" rel="nofollow noreferrer">https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html</a></p><p> 这建议.collect(Collectors.toList()</p><p> 我们该怎么做</p></div></object></string> - How can I convert ArrayList<String> to ArrayList<Object> using .collect(Collectors.toList() in Java stream

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用SET类从Type Setters&Getters类的“ Arraylist字符串对象”的Arraylist中获取唯一行 - How to get unique rows using SET class from an Arraylist of “Arraylist string objects” of Type Setters & Getters class 如何使用 java 7 从存储在 ArrayList 中的 Pojo 对象中获取键值对 - How to get key value pair from a Pojo objects stored in ArrayList using java 7 如何检索存储在Java ArrayList中的对象值 - How to retrieve objects values stored in a Java ArrayList ArrayList 对象如何存储在 Java 的 HashSet 中? - How the ArrayList objects are stored inside a HashSet in Java? 如何转换 ArrayList<string> 至 ArrayList<object> using.collect(Collectors.toList() 在 Java stream<div id="text_translate"><p> 如何在 Java stream 中使用.collect(Collectors.toList()将ArrayList&lt;String&gt;转换为ArrayList&lt;Object&gt;</p><p> 之前我用过</p><pre>CommonList = detailUtils.SelectIDValueGetterObservable(getActivity()).stream().forEach(i -&gt; CommonList.add(new foo(i));`</pre><p> 但是我遇到了这些<strong>副作用</strong></p><p> <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html" rel="nofollow noreferrer">https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html</a></p><p> 这建议.collect(Collectors.toList()</p><p> 我们该怎么做</p></div></object></string> - How can I convert ArrayList<String> to ArrayList<Object> using .collect(Collectors.toList() in Java stream 如何使用Java获取存储在ArrayList中的对象的属性 - How to get properties of an object stored in ArrayList using Java 使用 Java 流过滤对象的 ArrayList 以返回字符串类型的 ArrayList - Filter an ArrayList of Objects using Java Streams to return an ArrayList of type String 如何在java中将ArrayList转换为String [],Arraylist包含VO对象 - How to convert ArrayList to String[] in java, Arraylist contains VO objects 如何在Java类中声明对象的ArrayList? - How to declare an ArrayList of objects inside a class in java? 如何在Java中定义嵌套类对象的arraylist? - How to define an arraylist of nested class objects in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM