繁体   English   中英

将 String 与 ArrayList 的元素进行比较并返回 String

[英]Compare a String to the elements of the ArrayList and return a String

我有一个使用此代码创建的 arrayList:

public List<String> Apps = new ArrayList<String>();

此列表包含以下格式的字符串:

Data1+Description1
Data2+Description2
Data3+Description3
Data4+Description4
Data5+Description5
.... 

假设上面的字符串有 3 个部分。 第一部分是数据部分。 第二部分是+ 符号,第三部分是描述部分

我在代码的其他地方有另一个函数,它返回一个字符串。 现在这个字符串的形式是:

Retrieved_Name

Retrieved_Name将始终与上面的 Data1...Data n 之一匹配。即它将与上述字符串的第一部分匹配,直到 + 符号之前。

注意:此 Retrieved_Name 字符串始终与上述字符串匹配,直到出现 + 号。 而不是在那之后。

我的问题是,每当 Retrieved_Name 与上述字符串的第一部分匹配时,我需要返回第三部分。即字符串的描述部分。

我该如何实施?

import java.util.*;
import java.lang.*;
import java.io.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String s="anupam+singh"; /* here the string is composed of three parts*/
        String s1="anupam"; /* this is the first part of the string, in your case it is retrieved name */
        
        if(s.substring(0,s.indexOf("+")).equals(s1)) /*we use a substring function of String class, it takes two arguments starting and end index and returns the substring from the given string, the end index is exclusive*/
        {
            String s2=s.substring(s.indexOf("+")+1); /*the substring function can work on one argument even, if you just give the starting index then it will return the substring from that starting index till the end of string */
            System.out.println(s2);
        }
    }
}

我已经在评论中解释了代码。 希望能帮助到你。

我认为您应该使用 Map 来检索值,而不是通过 ArrayList 循环。

这将是 HashMap 的完美候选者。

应用程序

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AppUtils {
    public static Map<String, String> hMap = null;
    public static String TOKEN = "\\+";

    public static void main(String[] args) {

        List<String> apps = new ArrayList<String>();
        apps.add("Data1+Description1");
        apps.add("Data2+Description2");
        apps.add("Data3+Description3");
        apps.add("Data4+Description4");

        populateKeyValue(apps);
        String retrieved_Name = "Data1";
        System.out.println("Key : "+ retrieved_Name + ", Value : "+hMap.get(retrieved_Name));
        retrieved_Name = "Data3";
        System.out.println("Key : "+ retrieved_Name + ", Value : "+hMap.get(retrieved_Name));
    }

    public static void populateKeyValue(List<String> list) {
        hMap = list.stream().map(s -> s.split(TOKEN, -1))
                .filter(strings -> strings.length == 2)
                .collect(HashMap::new, (hashMap, str) -> hashMap.put(str[0],str[1]), HashMap::putAll);
    }
}

输出

键:数据1,值:描述1

键:数据3,值:描述3

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM