简体   繁体   English

仅打印ArrayList中元素的设置值?

[英]Printing only a set value of elements in an ArrayList?

I just want to know how to print out Strings in an ArrayList with a given certain value only for the output. 我只想知道如何仅在输出中打印出具有给定特定值的ArrayList中的字符串。 For example: I input "Hot", "Cold", "Pressure", "Pain". 例如:我输入“热”,“冷”,“压力”,“疼痛”。 What method/control statement should I use to make so that the output will only be the words with four letters? 我应该使用哪种方法/控制语句,以便输出仅是四个字母的单词?

Output: "Cold" "Pain" 输出:“冷”“痛”

It only prints "Cold" & "Pain" because they're the only one with four elements. 它仅打印“冷”和“疼痛”,因为它们是唯一具有四个元素的一个。 Will the use of .set be useful? 使用.set会有用吗?

  • You can add Strings to a map. 您可以将字符串添加到地图。 The key can be the length of the string and the value a list of strings. 键可以是字符串的长度,值可以是字符串列表。

Map<Integer, List<String>> -> Map<string length, List<String>>

This one is expected O(1) runtime 预期此O(1)运行时

  • You can keep the strings in a list and traverse them: 您可以将字符串保留在列表中并遍历它们:
List list = ...

    for (String s: list){
        if (s.length()==4){
              print(s);
        }
    }

This one has linear runtime 这具有线性运行时

As explained in the comments, you could iterate over the list. 如评论中所述,您可以遍历列表。 If this is a repeated operation, you could use a map to sort the strings by length. 如果这是重复操作,则可以使用映射按长度对字符串进行排序。 See below an example with the 2 solutions: 请参阅以下带有2个解决方案的示例:

public static void main(String[] args) {
    List<String> list = Arrays.asList("Hot", "Cold", "Pressure", "Pain");

    //Solution 1
    for (String s : list) {
        if (s.length() == 4) {
            System.out.println(s); //prints Cold and Pain
        }
    }

    //Solution 2
    Map<Integer, List<String>> map = new HashMap<Integer, List<String>> ();
    for (String s : list) {
        int length = s.length();
        if (map.containsKey(length)) {
            map.get(length).add(s);
        } else {
            map.put(length, new ArrayList<String>(Arrays.asList(s)));
        }
    }

    System.out.println(map.get(4)); //prints [Cold, Pain]
    System.out.println(map.get(3)); //prints [Hot]
}

I'd also check for nulls (don't know if they could occur in your situation) to avoid a possible java.lang.NullPointerException: 我还将检查null(不知道它们是否可能在您的情况下发生),以避免可能的java.lang.NullPointerException:

    List<String> list = Arrays.asList("Hot", "Cold", "Pressure", null, "Pain");

    for (String s : list) {
        if (s != null && s.length() == 4) {
            System.out.println(s); // prints "Cold" and "Pain"
        }
    }

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

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