从Arraylist <string>获取恰好出现三遍的字符串

时间:2019-01-02 16:29:00

标签: java list arraylist

我有一个ArrayList,其中包含一些重复值和三次出现的值,我想将三次出现的值专门收集到另一个ArrayList中,例如

Arraylist<String> strings;   //contains all strings that are duplicates and that occur thrice

在这里,我只想获取在另一个数组列表中三次出现的字符串。

Arraylist<String> thrice;    //contains only elements that occur three times.

当前,我有一个solution用于处理重复项,但我不能仅将其复制三次就不能扩展它,这请帮我找出来。

5 个答案:

答案 0 :(得分:3)

您可以通过流执行以下操作:

 List<String> result = strings.stream()
                .collect(Collectors.groupingBy(Function.identity(), counting()))
                .entrySet().stream()
                .filter(e -> e.getValue() == 3) // keep only elements that occur 3 times
                .map(Map.Entry::getKey)
                .collect(Collectors.toList());

您也可以按照以下步骤进行操作,但是我建议您使用上面的方法,因为它更可取。

List<String> result = new HashSet<>(strings).stream()
                            .filter(item -> strings.stream()
                                  .filter(e -> e.equals(item)).limit(3).count() == 3)
                          .collect(Collectors.toList());

答案 1 :(得分:2)

基本上,您现在不想使用 HashSet 来使用 HashMap 来计算每个字符串的出现次数。< / p>

此外,您无需编写一种方法来查找出现三次的特定字符串,而是可以编写一个方法,该方法采用一个参数n来查找出现 N 的字符串。时间:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

class StackOverflowQ {

  static List<String> getStringsThatOccurNTimes(List<String> stringList, int n) {
    if (stringList == null || stringList.size() == 0) {
      return stringList;
    }
    Set<String> stringsThatOccurNTimesSet = new HashSet<>();
    Map<String, Integer> stringCounts = new HashMap<>();
    for (String s : stringList) {
      int currentStringCount = stringCounts.getOrDefault(s, 0) + 1;
      stringCounts.put(s, currentStringCount);
      if (currentStringCount == n) {
        stringsThatOccurNTimesSet.add(s);
      } else if (currentStringCount == n + 1) {
        stringsThatOccurNTimesSet.remove(s); // We use a set so this operation is O(1)
      }
    }
    return new ArrayList<>(stringsThatOccurNTimesSet);
  }

  public static void main(String[] args) {
    List<String> stringsList = new ArrayList<>(Arrays.asList("a", "b", "c", "d", "e", "b", "c", "c", "d", "d", "d", "e"));
    List<String> stringsThatOccurTwoTimes = getStringsThatOccurNTimes(stringsList, 2);
    List<String> stringsThatOccurThreeTimes = getStringsThatOccurNTimes(stringsList, 3);
    List<String> stringsThatOccurFourTimes = getStringsThatOccurNTimes(stringsList, 4);
    System.out.println("Original list: " + stringsList);
    System.out.println("Strings that occur two times: " + stringsThatOccurTwoTimes);
    System.out.println("Strings that occur three times: " + stringsThatOccurThreeTimes);
    System.out.println("Strings that occur four times: " + stringsThatOccurFourTimes);
  }

}

输出:

Original list: [a, b, c, d, e, b, c, c, d, d, d, e]
Strings that occur two times: [b, e]
Strings that occur three times: [c]
Strings that occur four times: [d]

答案 2 :(得分:1)

最好的方法是.....

制作所需的数组列表.........

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.motion.MotionLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/motionLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:fitsSystemWindows="true"
    app:layoutDescription="@xml/scene_01"
    tools:context=".MainActivity">

    <android.support.constraint.ConstraintLayout
        android:id="@+id/materialCardView2"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintVertical_weight="2.5"
        android:background="@color/white"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView4">

        <android.support.design.card.MaterialCardView
            android:id="@+id/materialCardView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginStart="16dp"
            android:layout_marginTop="32dp"
            android:layout_marginEnd="16dp"
            app:cardBackgroundColor="@color/white"
            app:cardCornerRadius="4dp"
            app:cardElevation="0dp"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:strokeColor="@color/colorPrimary"
            app:strokeWidth="2dp">

            <android.support.constraint.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent">

                <TextView
                    android:id="@+id/num"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="16dp"
                    android:layout_marginTop="16dp"
                    android:text="Phone Number"
                    app:layout_constraintStart_toStartOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                <TextView
                    android:id="@+id/textView4"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="16dp"
                    android:text=":"
                    app:layout_constraintBottom_toBottomOf="@+id/num"
                    app:layout_constraintStart_toEndOf="@+id/num"
                    app:layout_constraintTop_toTopOf="@+id/num"
                    app:layout_constraintVertical_bias="0.0" />

                <TextView
                    android:id="@+id/textView5"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:text="Email ID"
                    app:layout_constraintEnd_toEndOf="@+id/num"
                    app:layout_constraintHorizontal_bias="0.0"
                    app:layout_constraintStart_toStartOf="@+id/num"
                    app:layout_constraintTop_toBottomOf="@+id/num" />

                <TextView
                    android:id="@+id/textView6"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=":"
                    app:layout_constraintEnd_toEndOf="@+id/textView4"
                    app:layout_constraintStart_toStartOf="@+id/textView4"
                    app:layout_constraintTop_toTopOf="@+id/textView5" />

                <TextView
                    android:id="@+id/textView7"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:layout_marginBottom="16dp"
                    android:text="Batch"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="@+id/textView5"
                    app:layout_constraintHorizontal_bias="0.0"
                    app:layout_constraintStart_toStartOf="@+id/textView5"
                    app:layout_constraintTop_toBottomOf="@+id/textView5" />

                <TextView
                    android:id="@+id/textView8"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text=":"
                    app:layout_constraintEnd_toEndOf="@+id/textView6"
                    app:layout_constraintStart_toStartOf="@+id/textView6"
                    app:layout_constraintTop_toTopOf="@+id/textView7" />

                <TextView
                    android:id="@+id/textView9"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="16dp"
                    android:layout_marginTop="16dp"
                    android:layout_marginEnd="16dp"
                    android:text="90000000000"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="0.0"
                    app:layout_constraintStart_toEndOf="@+id/textView4"
                    app:layout_constraintTop_toTopOf="parent" />

                <TextView
                    android:id="@+id/textView10"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="16dp"
                    android:layout_marginEnd="16dp"
                    android:text="username@gmail.com"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintHorizontal_bias="1.0"
                    app:layout_constraintStart_toEndOf="@+id/textView6"
                    app:layout_constraintTop_toTopOf="@+id/textView6" />

                <TextView
                    android:id="@+id/textView11"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_marginStart="16dp"
                    android:layout_marginTop="16dp"
                    android:layout_marginEnd="16dp"
                    android:layout_marginBottom="16dp"
                    android:text="Kolkata"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    app:layout_constraintStart_toEndOf="@+id/textView8"
                    app:layout_constraintTop_toBottomOf="@+id/textView10" />
            </android.support.constraint.ConstraintLayout>
        </android.support.design.card.MaterialCardView>

        <android.support.design.button.MaterialButton
            android:id="@+id/button5"
            style="@style/Button"
            android:layout_width="0dp"
            android:layout_height="74dp"
            android:layout_marginEnd="16dp"
            android:text="Payment Status"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toEndOf="@+id/button2"
            app:layout_constraintTop_toTopOf="@+id/button2" />

        <android.support.design.button.MaterialButton
            android:id="@+id/button2"
            style="@style/Button"
            android:layout_width="0dp"
            android:layout_height="74dp"
            android:layout_marginStart="16dp"
            android:layout_marginTop="32dp"
            android:layout_marginEnd="16dp"
            android:text="Admission Details"
            app:layout_constraintEnd_toStartOf="@+id/button5"
            app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/materialCardView" />

        <android.support.design.button.MaterialButton
            android:id="@+id/button3"
            style="@style/Button"
            android:layout_width="0dp"
            android:layout_height="74dp"
            android:layout_marginTop="16dp"
            android:text="Rules and Regulation"
            app:layout_constraintEnd_toEndOf="@+id/button2"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintStart_toStartOf="@+id/button2"
            app:layout_constraintTop_toBottomOf="@+id/button2" />

        <android.support.design.button.MaterialButton
            android:id="@+id/button4"
            style="@style/Button"
            android:layout_width="0dp"
            android:layout_height="74dp"
            android:text="Leave"
            app:layout_constraintEnd_toEndOf="@+id/button5"
            app:layout_constraintStart_toStartOf="@+id/button5"
            app:layout_constraintTop_toTopOf="@+id/button3" />

        <android.support.design.button.MaterialButton
            android:id="@+id/button6"
            style="@style/Button"
            android:layout_width="184dp"
            android:layout_height="74dp"
            android:layout_marginStart="64dp"
            android:layout_marginTop="16dp"
            android:layout_marginEnd="64dp"
            android:text="Attendance"
            app:layout_constraintEnd_toEndOf="@+id/button4"
            app:layout_constraintStart_toStartOf="@+id/button3"
            app:layout_constraintTop_toBottomOf="@+id/button3" />


        <android.support.design.button.MaterialButton
            android:id="@+id/button7"
            style="@style/Widget.MaterialComponents.Button.UnelevatedButton"
            android:layout_width="wrap_content"
            android:layout_height="50dp"
            android:layout_marginEnd="12dp"
            android:text="Log out"
            app:icon="@drawable/exit"
            app:layout_constraintBottom_toTopOf="@+id/space3"
            app:layout_constraintEnd_toEndOf="@+id/materialCardView" />

        <Space
            android:id="@+id/space3"
            android:layout_width="1dp"
            android:layout_height="15dp"
            android:layout_marginStart="8dp"
            app:layout_constraintBottom_toBottomOf="@+id/materialCardView"
            app:layout_constraintEnd_toEndOf="@+id/materialCardView"
            app:layout_constraintHorizontal_bias="0.882"
            app:layout_constraintStart_toStartOf="@+id/button7"
            app:layout_constraintTop_toTopOf="@+id/materialCardView"
            app:layout_constraintVertical_bias="0.227" />
    </android.support.constraint.ConstraintLayout>

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        app:layout_constraintVertical_weight="1"
        android:scaleType="centerCrop"
        app:layout_constraintBottom_toTopOf="@+id/materialCardView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.0"
        app:srcCompat="@drawable/loginn" />

    <Space
        android:id="@+id/space"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="@+id/imageView4"
        app:layout_constraintEnd_toEndOf="@+id/imageView4"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="@+id/imageView4"
        app:layout_constraintTop_toTopOf="@+id/imageView4"
        app:layout_constraintVertical_bias="1.0" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginEnd="16dp"
        android:layout_marginBottom="8dp"
        android:text="Firstname Lastname"
        android:textSize="20sp"
        android:textStyle="bold"
        android:textColor="@color/white"
        app:layout_constraintBottom_toTopOf="@+id/materialCardView2"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView4"
        app:layout_constraintVertical_bias="1.0" />

    <com.mikhaellopez.circularimageview.CircularImageView
        android:id="@+id/profileImage"
        android:layout_width="133dp"
        android:layout_height="0dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="8dp"
        android:padding="16dp"
        android:src="@drawable/loginn"
        app:civ_border_color="@color/white"
        app:civ_border_width="1dp"
        app:civ_shadow="true"
        app:civ_shadow_color="#000000"
        app:civ_shadow_radius="0"
        app:layout_constraintBottom_toTopOf="@+id/textView"
        app:layout_constraintEnd_toEndOf="@+id/space"
        app:layout_constraintStart_toStartOf="@+id/space"
        app:layout_constraintTop_toTopOf="@+id/space"
        app:layout_constraintVertical_bias="1.0" />
</android.support.constraint.motion.MotionLayout>

添加一些值进行检查....

    ArrayList<String> thrice=new ArrayList<>();
    ArrayList<String> one=new ArrayList<>();

映射完成任务.....

    one.add("1");one.add("1");one.add("1");one.add("1");one.add("1");
    one.add("2");one.add("2");one.add("2");one.add("2");one.add("2");
    one.add("1");one.add("1");one.add("1");
    one.add("3");one.add("3");
    one.add("4");one.add("5");
    one.add("2");one.add("2");one.add("2");

在列表视图中设置列表...

    Map<String, Integer> duplicates = new HashMap<String, Integer>();

    for (String str : one) {
        if (duplicates.containsKey(str)) {
            duplicates.put(str, duplicates.get(str) + 1);
        } else {
            duplicates.put(str, 1);
        }
    }

    for (Map.Entry<String, Integer> entry : duplicates.entrySet()) {

                       if(entry.getValue()>=3){
                             thrice.add(entry.getKey());
                           }
    }

输出= 1,2

已经检查了答案,您可以根据自己的方式更改条件

    ArrayAdapter<String> ad=new ArrayAdapter<> 
    (this,android.R.layout.simple_list_item_1,thrice);
    ListView lv=findViewById(R.id.new_l);
    lv.setAdapter(ad);

上面最简单的答案...不需要为Android用户更改最低sdk的版本

答案 3 :(得分:0)

您可以为此使用computeIfAbsent

List<String> strings;

final Map<String, BigInteger> stringCounts = new HashMap<>();
strings.stream().forEach(s -> {
  BigInteger count = stringCounts.computeIfAbsent(s, k -> BigInteger.ZERO).add(BigInteger.ONE);
  stringCounts.put(s, count);
});

现在使用stringCounts过滤value=3

答案 4 :(得分:0)

您要尝试解决的两个问题中的通用工具将Collections.frequency用作:

/**
 * @param input the list as your input
 * @param n number of occurrence (duplicates:2 , triplets:3 etc..)
 * @param <T> (type of elements)
 * @return elements with such conditional occurrent in a Set
 */
static <T> Set<T> findElementsWithNOccurrence(List<T> input, int n) {
    return input.stream()
            .filter(a -> Collections.frequency(input, a) == n) // filter by number of occurrences
            .collect(Collectors.toSet()); // collecting to a final set (one representation of each)
}

注意 :这将是一种 O(n^2) 的方法,因为它使用了Collections.frequency来遍历整个集合再次获得频率。但建议针对您要的内容采用更具可读性和通用性的方法。此外,这有意将最终输出收集到Set,因为List毕竟可以再次具有重复项。


或者,您可以使用方法count the frequency of elements in Java-8并迭代创建的Map的条目,从而根据需要处理过滤并在同一迭代中收集输出:

/**
 * @param input the list as your input
 * @param n     number of occurrence (duplicates :2 , triplets :3 etc)
 * @param <T>   (type of elements)
 * @return elements in a set
 */
static <T> Set<T> findElementsWithNOccurrence(List<T> input, int n) {
    return input.stream() // Stream<T>
            .collect(Collectors.groupingBy(Function.identity(), 
                    Collectors.counting())) // Map<T, Long>
            .entrySet() // Set<Map.Entry<T,Long>>
            .stream() // Stream<Map.Entry<T,Long>>
            .filter(e -> e.getValue() == n) // filtered with frequency 'n'
            .map(Map.Entry::getKey) // Stream<T>
            .collect(Collectors.toSet()); // collect to Set
}